JavaScript - 数组“未定义”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28933486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - Array "undefined" error
提问by qua1ity
I got a problem with this simple piece of code which i cant figure out. Instead of printing the whole array in the console, i get the message "10 undefined". Altough if i put "var i" to 0 or below then it's all good and i get a full list from that number up to 10.
我在这段简单的代码中遇到了一个我无法弄清楚的问题。我没有在控制台中打印整个数组,而是收到消息“10 未定义”。尽管如果我将“var i”设为 0 或更低,那么一切都很好,我会得到一个从该数字到 10 的完整列表。
Why wont this work when "i" is set to a number above 0? Took a picture of my console in chrome to show how it looks like:
当“i”设置为大于 0 的数字时,为什么这不起作用?用 chrome 拍了一张我的控制台的照片,以显示它的样子:


var ar = [];
for (var i = 1; i <= 10; i++) {
ar.push(i);
console.log(ar[i]);
}
回答by nnnnnn
JavaScript array indices start at 0, not 1. The .push()methodadds an element at the end of the array, which in the case of an empty array (as yours is when your loop begins) will be array element 0.
JavaScript 数组索引从 0 开始,而不是 1。该.push()方法在数组末尾添加一个元素,在空数组的情况下(就像您的循环开始时一样)将是数组元素 0。
Your loop inserts the value 1at array index 0, the value 2at array index 1, and so forth up to the value 10at array index 9.
您的环插入值1数组索引0,该值2在数组索引1,和依此类推,直到所述值10在数组索引9。
Each of your console.log(ar[i])statements is trying to log a value from an index one higher than the highest element index, and those elements will always be undefined. So the console logs the value undefinedten times.
您的每个console.log(ar[i])语句都试图从比最高元素索引高一个的索引中记录一个值,而这些元素将始终为undefined. 所以控制台会记录该值undefined十次。
You can log the last element of an array like this:
您可以像这样记录数组的最后一个元素:
console.log(ar[ar.length-1]);
Or in your case where you (now) know that iwill be one higher than the index that .push()used:
或者在您(现在)知道这i将比使用的索引高 1 的情况下.push():
console.log(ar[i-1]);
回答by John B
"10 undefined" means that the console showed "undefined" 10 times.
“10 undefined”表示控制台显示“undefined”10次。
As thefourtheye says in his comment, you're pushing the value ibut the index of the element that you just pushed onto the end of the array is i - 1. This means that each time you console.log(ar[i])you're logging something that's not yet defined.
正如 thefourtheye 在他的评论中所说,您正在推送值,i但您刚刚推送到数组末尾的元素的索引是i - 1. 这意味着每次您console.log(ar[i])记录尚未定义的内容时。
This is all because the first element in the array is ar[0], not ar[1]. You can fix your problem by logging like so: console.log(ar[ i - 1 ]);
这都是因为数组中的第一个元素是 ar[0],而不是 ar[1]。您可以通过像这样记录来解决您的问题:console.log(ar[ i - 1 ]);
回答by gone43v3r
Because array indices start at zero. The current index is undefined that's why you get those. Try this instead:
因为数组索引从零开始。当前索引未定义,这就是您获得这些索引的原因。试试这个:
var ar = [];
for(var i = 1;i <= 10;i++){
ar.push(i);
console.log(ar[i-1]);
}

