javascript - For 循环问题 JavaScript

标签 javascript

[

  // Define the variables
  var stringIn = [];
  var finalMessage = "Thanks for participating!";
  
  // Get input from user
  stringIn[0] = prompt("Enter the first string:");
  stringIn[1] = prompt("Enter the second string:");
  stringIn[2] = prompt("Enter the third string:");
  stringIn[3] = prompt("Enter the fourth string:");
  stringIn[4] = prompt("Enter the fifth string:");
  
  // For loop and display
  for(var myCounter = 0; myCounter < 5; myCounter++) {
    document.write("You entered: " + stringIn + "\n");
  }
  
  document.write("\n" + finalMessage);

我的输出应该是: 您输入的是:阿尔法 您输入的是: 布拉沃 您输入的是:查理 您输入: 达美航空 您输入:回声

但我得到:

您输入了:Alpha、Bravo、Charlie、Delta、Echo 您输入了:Alpha、Bravo、Charlie、Delta、Echo 您输入了:Alpha、Bravo、Charlie、Delta、Echo 您输入了:Alpha、Bravo、Charlie、Delta、Echo 您输入了:Alpha、Bravo、Charlie、Delta、Echo

我添加了代码来帮助解决我的问题。 FireFox Web 控制台没有显示任何错误,如果出现错误,则不会有任何输出。这段代码有什么问题?

最佳答案

您只需要在迭代器中访问 stringIn 的索引即可。

stringIn[myCounter]

  // Define the variables
  var stringIn = [];
  var finalMessage = "Thanks for participating!";
  
  // Get input from user
  stringIn[0] = prompt("Enter the first string:");
  stringIn[1] = prompt("Enter the second string:");
  stringIn[2] = prompt("Enter the third string:");
  stringIn[3] = prompt("Enter the fourth string:");
  stringIn[4] = prompt("Enter the fifth string:");
  
  // For loop and display
  for(var myCounter = 0; myCounter < 5; myCounter++) {
    document.write("You entered: " + stringIn[myCounter] + "\n");
  }
  
  document.write("\n" + finalMessage);

关于javascript - For 循环问题 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59165119/

相关文章:

javascript - 如何清空关注复选框更改的切换文本框?

javascript - 组件中的数据对象未定义

javascript - 如何使用tab键进入下一个标签

Javascript 事件处理程序 `this` 闭包内的绑定(bind)不起作用

javascript - 如何在 "pdfmake"javascript库中设置水印的字体大小

javascript - JS 为类的每个属性定义 getter

javascript - 有什么方法可以快速确定浏览器是否支持支持 CORS 的图像而不污染浏览器?

javascript - 防止默认输入键事件而不阻止滚动

javascript - Socket IO 1.2 查询参数

javascript - 如何让这个功能更可重用/更具体/更好的设计?