开发者

javascript var alerts but when used is undefined

This is weird. Check this out:

 for( var i = 0; i <= videos.length; i ++ ){

    alert(videos[i].id); // this works and alerts the correct number

    var foo = videos[i].id; // firebug says 开发者_高级运维"videos[i] is undefined"

 }

There are 3 videos. In FF this alerts all 3 video id's then fails saying that videos[i] is undefined. No Idea, at all.


Get rid of the = in your for loop condition.

for( var i = 0; i < videos.length; i ++ ){
    ...
}

With <=, you are iterating to the index, one larger than the actual index value of the Array, so you are iterating over an invalid index which returns undefined.

For example...

If you have array('A','B','C'), the length is 3. Now, if you iterate to 3 <= i, and include 0, as arrays begin with in Javascript, you will actually loop 4 times, not three.

The index value of A is 0, not 1, so you need to stop BEFORE i is equal to the length, not continue until i is equal to the length, since the 0 index is essentially added to the total length for the looping, meaning 3+1. 4 loops over this array would be one too many, hence the < and not <=. You want to STOP before 4, not stop AFTER 4 but before 5.

Also, it is generally good practice to cache the length of the Array, because some browsers do not optimise it.


Since you are doing i <= videos.length, you are reading one past the end of the videos array. Javascript arrays are zero-indexed, so you will usually want to iterate up to length - 1.

Instead, try:

for( var i = 0; i < videos.length; i ++ ){
    alert(videos[i].id); // this works and alerts the correct number
    var foo = videos[i].id; // firebug says "videos[i] is undefined"
}


Change the "<=" to "<" in the for loop. It should fix the problem.

The problem is that you have only three items in the array. You begin by addressing the first item with 0. This means that 2 is the last valid index. When the code tries to access index 3, it fails. (That failure point would be at the 4th time through the loop, when the alert(...) tries to access a nonexistent 4th element (at position 3).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜