For循环发行JavaScript

问题描述 投票:0回答:2

[

  // 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您输入了:回声

但我得到:

您输入: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控制台不显示任何错误,如果出现错误,则不会有任何输出。此代码有什么问题?

javascript
2个回答
0
投票

您只需要在迭代器中访问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);

0
投票

应该是

  for(var myCounter = 0; myCounter < 5; myCounter++) {
    document.write("You entered: " + stringIn[myCounter] + "\n");
  }
© www.soinside.com 2019 - 2024. All rights reserved.