javascript - 使用 forEach 循环遍历 Array(n),未定义值的数组

标签 javascript arrays

<分区>

我想使用数组构造函数 Array() 快速构造一个长度为 n 的数组,然后循环生成的数组。

根据 MDN's docs :

If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with length set to that number. If the argument is any other number, a RangeError exception is thrown.

据推测,执行 Array(5) 会创建一个长度为 5 的数组,它会这样做。

var arr = new Array(5);

console.log(arr); // [undefined x 5]
console.log(arr.length); // 5

但是,当我尝试遍历结果数组并注销值或索引时,没有任何反应。

arr.forEach(function(v, i) { console.log(v, i); });

// nothing logs to the console

或者,如果我使用数组文字,并尝试循环遍历这些值,它会按预期记录:

[undefined, undefined].forEach(function(v, i) { console.log(v, i); });

// undefined 0
// undefined 1

为什么我不能遍历由 Array 构造函数创建的数组?


This answer解释了 map 出现的一些浏览器奇怪现象,例如:

arr.map(function(v, i) { return i; }) // returns [undefined x 5]

但我特别感兴趣的是,为什么 forEach 循环根本不对这些值进行迭代

最佳答案

我知道我没有直接回答这个问题,但我仍然相信这提供了很好的信息。

Check what Kyle Simpson said recently about this topic.

基本上,

console.log(new Array(5))  // Chrome: [undefinedx5] Firefox: [ <5 empty slots> ]

console.log([undefined, undefined, undefined, undefined, undefined]) // [ undefined, undefined, undefined, undefined, undefined ] 

是完全不同的值类型。当浏览器说 undefinedx5 时,它(有点)在骗你。在第一种情况下应用 .map() 不会返回任何内容,而在第二种情况下,您可以对未定义的进行操作。

来自规范,ecma-262/5.1/#sec-15.4.2.2new Array(5) 做的唯一一件事就是创建一个长度属性为 5 的 Array 类类型的对象。文字数组语法 [] 实际上放置了类型(如果你给它东西)在插槽中。

关于javascript - 使用 forEach 循环遍历 Array(n),未定义值的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37491191/

相关文章:

c# - 二维数组 C# 的数组?

c++ - 在 C++ 中删除字符数组的内容

javascript - JS 字符串/数字和垃圾回收

javascript - PhantomJS 未加载动态内容

javascript - 使用内置样式的 Bootstrap 3 表单验证

java - 访问 LinkedHashMap 中最后一个对象中的方法

PHP : echo Multidimensional Array

javascript - 函数返回 "undefined"

javascript - Firebase 函数返回空数据对象

c++ - 使用双指针,从 **void 进行转换。 (未处理的异常 0xC0000005 : Access violation)