简体   繁体   English

javascript var警报,但使用时未定义

[英]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. 有3个视频。 In FF this alerts all 3 video id's then fails saying that videos[i] is undefined. 在FF中,此警报会警告所有3个视频ID,并提示未定义video [i]。 No Idea, at all. 一点都不知道。

Get rid of the = in your for loop condition. 摆脱for循环条件中的=

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 . 使用<= ,您要遍历索引,该索引比Array的实际索引值大一个,因此您遍历了返回undefined的无效索引。

For example... 例如...

If you have array('A','B','C') , the length is 3 . 如果您有array('A','B','C') ,则长度为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. 现在,如果迭代到3 <= i ,并且包含0 ,因为数组以Javascript开头,那么实际上将循环4次,而不是3次。

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. A的索引值为0 ,而不是1 ,因此您需要在i等于长度之前停止,直到i等于长度之前不要继续,因为0索引实际上已添加到循环的总长度中,这意味着3 + 1。 4 loops over this array would be one too many, hence the < and not <= . 该数组上的4个循环太多了,因此<和不是<= You want to STOP before 4, not stop AFTER 4 but before 5. 您想在4之前停止,而不是在4之后停止,而是在5之前停止。

Also, it is generally good practice to cache the length of the Array , because some browsers do not optimise it. 另外,缓存Array的长度通常是个好习惯,因为某些浏览器不会对其进行优化。

Since you are doing i <= videos.length , you are reading one past the end of the videos array. 由于您正在执行i <= videos.length ,因此您正在读取i <= videos.length数组末尾的videos Javascript arrays are zero-indexed, so you will usually want to iterate up to length - 1. Javascript数组的索引为零,因此通常需要迭代长度-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. 在for循环中将“ <=”更改为“ <”。 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. 首先以0寻址第一项。这意味着2是最后一个有效索引。 When the code tries to access index 3, it fails. 当代码尝试访问索引3时,它将失败。 (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). (当alert(...)尝试访问不存在的第4个元素(位置3)时,该故障点将是循环的第4次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM