array.push 不是函数 - 使用 reduce 时

array.push is not a function - when working with reduce

谁能帮我理解这是怎么回事?

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 is not a function"

并且检查第一个记录的 accumulator 表明我们有 push 方法 - 它是一个真正的函数:

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

修复很简单 - 将推送和 return 语句分开:

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

    return acc;
}, []);

console.log(secondArray);