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

时间:2017-07-02 21:51:48

标签: javascript arrays ecmascript-6 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不是函数”而崩溃

accumulator.push is not a function in reduce

检查第一个记录的accumulator表明我们有推送方法 - 这是一个真正的功能:

array.push not working with reduce

1 个答案:

答案 0 :(得分:27)

Array#push的返回值是推送后数组的新长度。这意味着在第二次迭代中private void OnRootGridLoading(FrameworkElement sender, object args) { var rootVisual = ElementCompositionPreview.GetElementVisual(Root); var clip = rootVisual.Compositor.CreateInsetClip(); rootVisual.Clip = clip; } 是一个数字,它没有推送方法。

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

acc