JavaScript减少带有

JavaScript减少带有

本文介绍了JavaScript减少带有/不带有初始值的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过JavaScript reduce函数求和一个数组的数字平方.但是,在调用reduce方法时,无论是否带有初始值,结果都不同.

var x = [75, 70, 73, 78, 80, 69, 71, 72, 74, 77];
console.log(x.slice().reduce((ac,n) => ac+(n*n))); // 49179
console.log(x.slice().reduce((ac,n) => ac+(n*n),0)); // 54729

这应该等同于上面的调用:

console.log(x.slice().map(val => val*val).reduce((ac,n) => ac+n)); // 54729

在这种情况下,两种方法都返回相同的值.

console.log([1,2,3].slice().reduce((ac,z) => ac+(z*z))); // 14
console.log([1,2,3].slice().reduce((ac,z) => ac+(z*z), 0)); // 14

为什么前两个电话的结果不同而后两个电话的结果相同?

解决方案

如果不向.reduce()提供第二个参数,它将使用数组的第一个元素作为累加器,并从第二个元素开始. /p>

在第一个示例中,.reduce()迭代的第一个结果是

75 + 70 * 70

而在第二个版本中,传递显式0的是

0 + 75 * 75

由此产生的计算级联会导致不同的结果.

在第二个示例中,您将结束计算

1 + 2 * 2

然后

5 + 3 * 3

在第一行中为14.在第二版本中,当您以0开头时,您将进行计算

0 + 1 * 1
1 + 2 * 2
5 + 3 * 3

也是14.

I am trying to sum the squares of numbers of an array by JavaScript reduce function. But the result differs when reduce method is called with or without the initial value.

var x = [75, 70, 73, 78, 80, 69, 71, 72, 74, 77];
console.log(x.slice().reduce((ac,n) => ac+(n*n))); // 49179
console.log(x.slice().reduce((ac,n) => ac+(n*n),0)); // 54729

This should be equivalent to the calls above:

console.log(x.slice().map(val => val*val).reduce((ac,n) => ac+n)); // 54729

In this case however both method returns the same value.

console.log([1,2,3].slice().reduce((ac,z) => ac+(z*z))); // 14
console.log([1,2,3].slice().reduce((ac,z) => ac+(z*z), 0)); // 14

Why are the results of the first two calls different and the last two the same?

解决方案

If you don't provide the second parameter to .reduce(), it uses the first element of the array as the accumulator and starts at the second element.

In the first example, your first result of the .reduce() iteration is

75 + 70 * 70

while in the second version where pass in an explicit 0 it's

0 + 75 * 75

The cascade of computations from that leads to different results.

In the second example, you'll end up computing

1 + 2 * 2

and then

5 + 3 * 3

in the first line, which gives 14. In the second version, when you start with 0, you'll compute

0 + 1 * 1
1 + 2 * 2
5 + 3 * 3

which is also 14.

这篇关于JavaScript减少带有/不带有初始值的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 18:22