javascript - `new Array(5).map()` 是如何工作的?

标签 javascript arrays

我最近发现映射一个未初始化的数组似乎并不像我预期的那样有效。使用此代码:

function helloMap(value, index) {
    return "Hello " + index;
}

console.clear();

var initialArray = Array.apply(null, new Array(5));

console.log("Array initialised with apply:");
console.log(initialArray);
console.log(initialArray.map(helloMap));

var normalArray = new Array(5);

console.log("Array constructed normally");
console.log(normalArray);
console.log(normalArray.map(helloMap));
.as-console-wrapper {
  max-height: 100% !important;
}

尽管每个数组的第一个输出是 [undefined, undefined, undefined, undefined, undefined],但我得到了不同的结果。

我得到不同结果的事实意味着这两个数组中的 undefined 实际上是不同的。首先我怀疑数组中有 5 个项目,每个项目都是未定义的。在第二个数组中有 5 个项目,但什么都没有,甚至没有未定义的......

这有点令人困惑。

谁能给我解释一下?

最佳答案

Array.apply(null, Array(5)) 实际上用您传入的第一个参数的值填充您作为第二个参数传递的数组(或类似数组的对象),从 MDN Docs 中可以看出.

new Array(5) 只是初始化一个数组,其长度属性设置为 5 的参数。同样,如在 MDN 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 its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values).

关于javascript - `new Array(5).map()` 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43256119/

相关文章:

Javascript 函数调试 - 为什么这个过滤器函数不能正常工作?

C++ 2011 : good syntax to initialize an array in a constructor?

javascript - Array.includes 无法按预期使用 html 文件上传和 localforage

javascript - 如何在 web2py 中将数据从 python 传递到 javascript

c# - 通过规范化(不使用 Linq)修改传入 double 组的过程

c# - 如何使用字符串数组来处理 C# 中 switch 语句中的大小写?

JAVA - 从字节数组创建 X509 证书

javascript - 如何在单个 Azure Web App 中托管 Express 静态站点和 API

javascript - 在JavaScript中,如何在特定时间运行函数?

javascript - 如何在 Meteor 中使对象具有反应性?