2017-07-02 11 views
3

ここで何が起こっているのか理解してもらえますか?array.pushは関数ではありません - 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をログに記録を検査するとプログラムがクラッシュは、我々がpushメソッドを持っていることを示している - それは本当の機能です。

array.push not working with reduce

+0

'リターンacc.concat(項目);' – fubar

+0

は 'プッシュ要素を返すpush'していますか?別の行を押してから、accを返してください。 – Carcigenicate

答えて

11

戻り値0 f Array#pushは、プッシュ後の配列の新しい長さです。つまり、2回目の繰り返しでは、accは数字であり、プッシュメソッドはありません。

修正は簡単です - プッシュを分離し、return文:

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

 
    return acc; 
 
}, []); 
 

 
console.log(secondArray);

+0

ああ!仰るとおり。ありがとう - 間違いなく受け入れられた答え – AIon

関連する問題