Ecmascript 6 控制台日志减少数组只返回最后一个值

Ecmascript 6 控制台日志减少数组只返回最后一个值,ecmascript-6,functional-programming,Ecmascript 6,Functional Programming,为了在js中尝试reduce,我尝试使用它将两个数组值相加。我知道很多不使用reduce的方法,我也认为使用reduce可以做到这一点,但问题是:当控制台记录reduced数组时,我只得到最后一个reduced值,我不知道为什么 let dblArray = [ [1, 2, 3], [4, 5, 6] ] let arr = dblArray[0].reduce((newArr, iter, index) => { // this returns 5, 7,

为了在js中尝试
reduce
,我尝试使用它将两个数组值相加。我知道很多不使用reduce的方法,我也认为使用reduce可以做到这一点,但问题是:当控制台记录reduced数组时,我只得到最后一个reduced值,我不知道为什么

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
有人能告诉我为什么吗?我想知道我的实现是否错误


谢谢

通过使用迭代器函数返回的值覆盖以前的值来减少工作。因此,当您到达最后一次迭代时,它只返回最后一个值

您需要在迭代器函数中构建一个数组,将前一个值和当前值连接起来,然后返回:

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)

谢谢,我没有发现之前的值被覆盖了。现在更清楚了:)你是说
map
reduce
应返回单个值。也许你可以展示工作代码,让我们知道你真正想做什么。减少,而不是映射。这就是整个工作代码。我接受了下面的答案;)