javascript - JavaScript 的 forEach 循环如何决定跳过或迭代数组中的 "undefined"和 "null"元素?

标签 javascript arrays foreach

我知道 forEach 方法将遍历数组对象并跳过所有 nullundefined 的数组元素。我在下面有一个例子:

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/

相关文章:

javascript - 防止事件在另一个事件正在运行时执行

javascript - electron-builder install-app-deps 尝试包含 react-native 而我在 webpack 中有一个别名设置为 react-native-electron

c - 运行以下代码时出现错误

javascript - 从 mysql 检索 javascript 字符串以进行后续编辑

javascript - 使用 JQuery 的语义 UI 下拉列表 - 如何使用 JQuery 初始化语义 UI 下拉列表

tinymce 按钮内的 JavaScript 循环

c - 使用 Malloc (char & int) 分配内存

PHP 停止 foreach()

c# - 在字符串数组中查找下一个可用日期

c# - 更改 Foreach 订单?