我知道 forEach
方法将遍历数组对象并跳过所有 null
或 undefined
的数组元素。我在下面有一个例子:
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
循环忽略未定义的第 4 个元素a[3]
。 - 但是,当执行
fn(b)
时,forEach
循环遍历第 4 个元素b[3]
,它也是未定义的.
这里的a[3]
和b[3]
有什么区别?为什么 forEach
循环没有跳过 b[3]
?
最佳答案
根据ECMAScript 5.1的规范,缺少的数组项被删除。
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]
的第一个示例的计算结果:
[1, 2, 3, undefined × 1, 5, 6]
但是,[1, 2, 3, undefined, 5, 6]
只是计算为:
[1, 2, 3, undefined, 5, 6]
正如我们所见,它们之间存在细微的差别,因此即使它们表面上看起来相似,行为也不相同。
关于javascript - JavaScript 的 forEach 循环如何决定跳过或迭代数组中的 "undefined"和 "null"元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38658103/