使用reduce时出现“array.push不是函数”的错误提示。

35

请问有人能帮我理解这里发生了什么吗?

let firstArray = [];
firstArray.push(1);
firstArray.push(1);
firstArray.push(1);
console.log("firstArray", firstArray); // result [ 1, 1, 1 ] - as expected.



let secondArray = [1, 2, 3].reduce((acc, item) => {

    console.log("acc", acc);
    console.log("typeof acc", typeof acc);

    // on first passing, the accumulator (acc) is Array[] == object.
    // on the second passing the acc == number.

    // but why?
    /// i expect to get [1,1,1] as my secondArray.
    return acc.push(1);

}, []);

console.log("secondArray", secondArray); 

该程序崩溃并显示“acc.push不是一个函数”。

accumulator.push is not a function in reduce

检查第一个记录的accumulator,发现我们有push方法 - 它是一个真正的函数:

array.push not working with reduce


4
item 添加到 acc 数组末尾并返回新的数组。 - fubar
push 方法会返回被推入的元素吗?请尝试将 push 操作和返回操作分开写在不同的行中。 - Carcigenicate
1个回答

77
Array#push 的返回值是 push 后数组的新长度。这意味着在第二次迭代中,acc 是一个数字,它没有 push 方法。

解决方法很简单——分离 push 和 return 语句:

const secondArray = [1, 2, 3].reduce((acc, item) => {
    acc.push(1);

    return acc;
}, []);

console.log(secondArray);


为什么 acc 的第二次迭代变成了一个数字? - tnkh
@Ori Drori - 刚刚看到了你的评论 - 为了不让初学者感到困惑:在上面的问题代码中没有 according.push() - accaccumulator 的缩写 - 这来自于函数式语言,其中 folding / reducing 是我们每天执行的基本操作之一,而 acc 是任何需要被 summed up / accumulated 的东西的通用名称。它被用于树、字典、状态机、数组、列表、任务等任何依赖的东西。这是一个非常普遍的模式。考虑到这是关于减少数组的问题,理解 acc 的含义非常重要。就是这样 :) - AIon
const secondArray = [1, 2, 3].reduce((acc, item) => (acc.push(1), acc), []);console.log(secondArray); - Tin Huynh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接