[英]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 個數字1
、 2
、 3
、 4
和5
,那么最終結果顯示,,,,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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.