2017-10-09 73 views
0

爲了在js中嘗試reduce,我試圖用它來將2個數組值加在一起。我知道有很多方法可以做到這一點,而不會減少,而我認爲還有減少的方法,但問題在於:當控制檯記錄減小的數組時,我只能得到最後一個減小的值,而我不知道爲什麼。控制檯日誌記錄減少的數組只返回最後一個值

let dblArray = [ 
    [1, 2, 3], 
    [4, 5, 6] 
] 

let arr = dblArray[0].reduce((newArr, iter, index) => { 
    // this returns 5, 7, 9 as expected 
    return iter + dblArray[1][index] 
}, []) 

console.log(arr) // this returns only 9 

有人能告訴我爲什麼?我想知道我的實施是否是錯誤的。

謝謝

+0

你的意思是'map'? 'reduce'是*假設*返回單個值。也許你可以顯示工作代碼,以便我們知道你真正想做什麼。 – Bergi

+0

減少,而不是映射。這是整個工作代碼。我接受了下面的答案;) – Neovea

回答

1

通過用迭代器函數返回的值覆蓋以前的值來減少工作量。因此,當你到達最後一次迭代時,它只返回最後一個值。

需要構建迭代函數內部的數組,加入先前值和當前值,則返回:

let dblArray = [ 
    [1, 2, 3], 
    [4, 5, 6] 
] 

let arr = dblArray[0].reduce((previousArray, iter, index) => { 
    // We can use array spread here to join the old array, 
    // and add the new value to it 
    return [...previousArray, iter + dblArray[1][index]]; 
    // On each iteration this would log: 
    // [5] 
    // [5, 7] 
    // [5, 7, 9] 
}, []) 

console.log(arr) 
+0

謝謝,我沒有得到以前的值被覆蓋。現在更清晰:) – Neovea

相關問題