减少新数组未正确执行

reduce on new Array not executing correctly

我需要不对数组成员执行 reduce 函数,而是只对索引执行。我尝试了以下方法:

const len = 4;
const arr = new Array(len);
const total = arr.reduce((accum, dummy, index) => calculate(accum, index), 0);

这行不通。我尝试添加一些打印输出,似乎 reduce 语句中的函数从未被调用。

如果我将 arr 替换为:

const arr = [0,1,2,3];

然后它工作正常。我错过了什么?我使用的数组长度确实验证为4,那为什么它没有按应有的方式执行4次函数?

new Array(len) 创建一个数组,其中 length 属性 为 len,但 没有 任何数组索引自有属性:

const arr = new Array(3);
console.log(arr.hasOwnProperty(1));

这称为 稀疏数组 ,并且几乎应该始终避免,因为创建它们会产生您正在经历的奇怪结果。可以先.fill数组,让数组从0到length - 1的每个数组索引值都赋值:

const arr = new Array(3).fill(0);
console.log(arr.hasOwnProperty(1));

然后 reduce 将能够遍历数组。

正如 specification 所说:

9. Repeat, while k < len,
  a. Let Pk be ! ToString(k).
  b. Let kPresent be ? HasProperty(O, Pk).
  c. ****If kPresent is true, then*****
    i. Let kValue be ? Get(O, Pk).
    ii. Set accumulator to ? `Call(callbackfn, undefined, « accumulator,   d. kValue, k, O »)`.

由于备用数组 没有 任何数组索引自有属性,因此永远不会调用 .reduce 回调(在规范中命名为 calllbackfn) .