【问题标题】:reduce on new Array not executing correctly减少新数组未正确执行
【发布时间】:2020-05-18 12:14:56
【问题描述】:

我需要在数组成员上而不是在索引上执行 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 次函数呢?

【问题讨论】:

  • reduce 函数在空数组上调用时返回初始值。如果您不将初始值传递给 reduce 函数并在空数组上调用 reduce,您将得到一个 TypeError

标签: javascript arrays reduce


【解决方案1】:

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)永远不会被调用。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-31
相关资源
最近更新 更多