【问题标题】:reduce function does not initialize accumulator to zero?减少函数不会将累加器初始化为零?
【发布时间】:2019-03-03 08:49:45
【问题描述】:

reduce 不会将累加器初始化为零?因为下面的例子发生了,我看不懂。

const r = (acc, curr) => acc |= (1 << curr);

let x;
x |= (1 << 0);

console.log(x); // -> 1 - OK
console.log([0].reduce(r)); // -> 0 - ???

以及如何按我的预期正确获得 1 而不做类似[0, 0].reduces(r); 的事情。

【问题讨论】:

  • reduce(r, 0) ...即您想初始化累加器(讽刺的是,答案就在您的问题中)
  • .reduce(func, initValue)?
  • @Jaromanda 是的,这是疏忽,谢谢。

标签: javascript ecmascript-6 reduce


【解决方案1】:

不,reduce 不默认累加器。当您只使用一个参数(回调)调用reduce 时,它对回调的第一次调用使用第一个条目作为累加器,第二个条目作为“添加”到它的值。当然,只有当数组至少有两个条目时才能这样做。当数组中只有一个条目并且您没有提供累加器默认值时,该条目的值是 reduce 的结果(并且根本不会调用您的回调)。这就是console.log([0].reduce(r)); 给你0 的原因。最后,如果你在一个空数组上调用reduce 并且没有提供默认值,那就是一个错误。 (这就是为什么 a.reduce((a, b) =&gt; a + b)a.reduce((a, b) =&gt; a + b, 0)相同的东西。)

例子:

// Outputs 1 without calling the callback
console.log([1].reduce((acc, value) => {
    console.log(`acc = ${acc}, value = ${value}`);
    return acc + value;
}));
// Outputs 3 after calling the callback with acc = 1 and value = 2
console.log([1, 2].reduce((acc, value) => {
    console.log(`acc = ${acc}, value = ${value}`);
    return acc + value;
}));

let a = [];
// Throws an error
try {
    console.log(a.reduce((a, b) => a + b));
} catch (error) {
    console.error(error);
}
// Works
try {
    console.log(a.reduce((a, b) => a + b, 0));
} catch (error) {
    console.error(error);
}
.as-console-wrapper {
    max-height: 100% !important;
}

【讨论】:

    猜你喜欢
    • 2018-07-29
    • 2022-06-13
    • 2014-03-13
    • 2015-06-04
    • 2020-01-18
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 2016-11-01
    相关资源
    最近更新 更多