最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript - Array "undefined" error - Stack Overflow

programmeradmin0浏览0评论

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.

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:

var ar = [];

for (var i = 1; i <= 10; i++) {
    ar.push(i);
    console.log(ar[i]);
}

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.

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:

var ar = [];

for (var i = 1; i <= 10; i++) {
    ar.push(i);
    console.log(ar[i]);
}
Share Improve this question edited Mar 9, 2015 at 0:20 AstroCB 12.4k20 gold badges58 silver badges74 bronze badges asked Mar 9, 2015 at 0:15 qua1ityqua1ity 6232 gold badges9 silver badges28 bronze badges 1
  • 4 You are pushing the value i, but the current index will be i - 1 – thefourtheye Commented Mar 9, 2015 at 0:16
Add a comment  | 

3 Answers 3

Reset to default 10

JavaScript array indices start at 0, not 1. The .push() method adds 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.

Your loop inserts the value 1 at array index 0, the value 2 at array index 1, and so forth up to the value 10 at array index 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 undefined ten times.

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 i will be one higher than the index that .push() used:

console.log(ar[i-1]);

"10 undefined" means that the console showed "undefined" 10 times.

As thefourtheye says in his comment, you're pushing the value i but 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.

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 ]);

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]);
}
发布评论

评论列表(0)

  1. 暂无评论