JavaScript的forEach循环如何决定跳过或遍历“未定义"循环.和“空"数组中的元素? [英] How does JavaScript's forEach loop decide to skip or iterate through "undefined" and "null" elements in an Array?
问题描述
我知道 forEach
方法将遍历数组对象,并跳过所有 null
或 undefined
的数组元素.我在下面有一个例子:
I know that forEach
method will iterate through an array object and will skip all array elements which are either null
or undefined
. I've an example below:
var a = [1,2,3,,5,6];
var b = [1,2,3,undefined,5,6];
var fn = function(arr){
arr.forEach(function(currentValue, index, array){
console.log(currentValue);
});
};
fn(a); //Prints on console (separated by newline): 1 2 3 5 6
fn(b); //Prints on console (separated by newline): 1 2 3 undefined 5 6
在上面的示例中,
- 在执行
fn(a)
时,forEach
循环会忽略未定义的第四个元素a [3]
. - 但是,当执行
fn(b)
时,forEach
循环遍历第四个元素b [3]
,该元素也是未定义的.
- when
fn(a)
is executed, theforEach
loop ignores the 4th elementa[3]
which is undefined. - But, when
fn(b)
is executed, theforEach
loop iterates through the 4th elementb[3]
which is also undefined.
这里的 a [3]
和 b [3]
有什么区别?为什么 forEach
循环没有跳过 b [3]
?
What is the difference between a[3]
and b[3]
here? Why forEach
loop didn't skip b[3]
?
推荐答案
According to the specifications of ECMAScript 5.1, missing array items are elided.
每当元素列表中的逗号前面没有AssignmentExpression时(即,逗号在另一个逗号的开头或之后),丢失的数组元素就会增加Array的长度并增加后续元素的索引.未定义省略的数组元素.
Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined.
由于它们是未定义的,因此行为是不可预测的,也没有关于是否应将它们视为普通数组项(如 undefined
)的定义.我怀疑在某些浏览器中,可能会返回undefined,但在Chrome中似乎并非如此.这是您的 [1、2、3、5、6]
的第一个示例的计算结果:
Since they are undefined, behaviour is unpredictable and there is no definition as to whether these should be treated as normal array items like undefined
. I suspect that in some browsers, undefined may be returned, but this doesn't appear to be the case in Chrome. Here's what your first example of [1, 2, 3,, 5, 6]
evaluates to:
[1, 2, 3, undefined × 1, 5, 6]
但是, [1、2、3,未定义,5、6]
的计算结果为:
[1, 2, 3, undefined, 5, 6]
正如我们所看到的,它们是微妙的不同,因此即使它们表面上看起来相似,其行为也不相同.
As we can see, these are subtly different, so the behaviour is not the same even though they look superficially similar.
这篇关于JavaScript的forEach循环如何决定跳过或遍历“未定义"循环.和“空"数组中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!