除了最后一个之外,所有数组元素都未定义?

All array elements undefined except the last one?

所以老师给我们布置了作业。我们应该编写一个程序,询问用户他们想要输入多少个数字,然后多次要求他们输入一个数字,直到它包含用户想要输入的所有数字。然后,程序应显示或输出用户先前输入或输入的数字。 我是这样做的:

<html>
<script>
  amount = prompt("How many numbers do you wish to input?");
  amount1 = amount - 1;
  for (i = 0; i <= amount1; i++) {
    a = i + 1;
    var input = [];
    input[i] = prompt("Please enter the " + a + ". number:");
  }
  alert(input.toString());
</script>

</html>

但是,输出不是我预期的那样。例如,如果我们输入 5 个数字,12345,那么最终结果显示 ,,,,5 如果我没记错的话,这意味着所有元素,除了最后一个,都是undefined。有谁知道为什么会发生这种情况以及如何避免这种情况?

只需将 var input = []; 变量初始化移出 for 循环即可。

为什么它对你不起作用: 因为你每次都用这一行重置输入数组的值 var input = []; 这就是为什么只有最后一个元素在数组中是可见的:(,所以当你从循环中移出时,它会按预期工作。

 amount = prompt("How many numbers do you wish to input?");
  amount1 = amount - 1;
  var input = [];
  for (i = 0; i <= amount1; i++) {
    a = i + 1;
    
    input[i] = prompt("Please enter the " + a + ". number:");
  }
  alert(input.toString());

<html>
<script>
    var input = [];  
    var a = 0;

    amount = Number(prompt("How many numbers do you wish to input?"));

    for (i = 0; i < amount; i++) {
        a = i + 1;
        input[i] = Number(prompt("Please enter the " + a + ". number:"));
    }

    alert(input.toString())
</script>
</html>