javascript - js reduce 中的默认参数被忽略

标签 javascript ecmascript-6

我一直在 JavaScript 中使用默认变量,但我无法让这个示例在任何东西上工作(节点 10.16.3、firefox 69、chrome 76)

let arr = [1, 2, 3];
arr.reduce( (acc = 5, el) => acc + el)  // -> 6

它会默默地失败,是的,我知道我可以通过在回调后传递一个初始值来完成同样的事情。我只是想知道为什么这不起作用。

最佳答案

如果该值未定义

acc = 5 只会使用5 作为默认值。

Array#reduce如果您不提供 arr.reduce(callback, initial) 形式的初始参数,则使用数组的第一个元素,并且迭代从数组的第二个元素:

let arr = [1, 2, 3];
arr.reduce( (acc = 5, el) => {
  console.log(acc, el);
  return acc + el;
})  // -> 6

因此,让 acc 成为 未定义 的唯一方法是通过初始参数显式设置它,或者如果第一个元素未定义:

let arr = [1, 2, 3];

let initialiseWithUndefined = [1, 2, 3].reduce( (acc = 5, el) => acc + el, undefined)  // -> 11
console.log(initialiseWithUndefined);

let firstItemIsUndefined = [undefined, 2, 3].reduce( (acc = 5, el) => acc + el)  // -> 10
console.log(firstItemIsUndefined);

关于javascript - js reduce 中的默认参数被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58291349/

相关文章:

javascript - Node.js |如何通过串口向设备发送和接收一个字节?

javascript - 在 Angular 2 中编写最基本的单元测试?

javascript - 使用 JavaScript ES6 模块导入现有库

javascript - 如何使用 es6 在 react-native 中初始化数组?

javascript - html/JS 中其他输入的只读等价物

javascript - 是否可以使用 React Native 应用程序操作 MySQL 数据?

javascript - 自动滚动水平 div

javascript - React.js : Passing Props from a Function to a Component

javascript - 无法使用带有 webpack 和 ES6 设置的 document.getElementById ('password').addEventListener() 调用函数

javascript - 给定维度上数组数据的聚合