为什么编码段落中的“array1.reduce(reducer)”在'array1'之后使用'.reduce'?似乎array1 doest不包含减少此对象

问题描述 投票:-2回答:1

const array1 = [1, 2, 3, 4];
const reducer = (previous, current) => previous + current;


// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

运行上面的代码时,它给出10然后15

javascript methods reduce
1个回答
1
投票

我认为你的执行方式有问题

Your Example:
const array1 = [1, 2, 3, 4];
const reducer = (previous, current) => previous + current;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));`enter code here`
// expected output: 15

正如你所说的那样,当你第一次申请.reduce时,为什么它不会减少。

因此,当你应用.reduce它不会改变原始数组但返回新创建的数组。所以减少器应用于新创建的数组而不是原始数组(array1)

因此,您可以使用以下代码检查输出,这可能会让您怀疑:

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => 
{
 console.log("Data is"+accumulator +' '+ currentValue); 
 return accumulator + currentValue;
}

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

其中accumulator是从reducer函数返回的值。 currentValue是数组的当前值。

© www.soinside.com 2019 - 2024. All rights reserved.