首页 > 解决方案 > 0 作为 reduce 函数的 initalValue 的作用是什么?

问题描述

为了学习reduce功能,我尝试了这个w3schools 示例

<!DOCTYPE html>
<html>
<body>

<p>Click the button to get the sum of the rounded numbers in the array.</p>
<button onclick="myFunction()">Try it</button>

<p>Sum of numbers in array: <span id="demo"></span></p>

<script>
var numbers = [15.5, 2.3, 1.1, 4.7];

function getSum(total, num) {
  return total + Math.round(num);
}
function myFunction(item) {
  document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);
}
</script>

</body>
</html>

在这个例子中,如果我们传递 0,initalValue它返回 24,但如果我们使用它的默认值initalValue,结果将是 23.5!所以我无法得到零点以及为什么它会改变结果!已经不initialValue等于0了?

标签: javascriptreduce

解决方案


没有。的初始值accumulator是 中的第一个元素,array它从第二个元素开始,直到显式地给了一个值accumulator(在这种情况下为 0)。当没有给出值时,accumulator一开始已经是 15.5,但是当你给它 value 时0,它​​从那里开始,因此结果有所不同。

第一次调用回调时,accumulator 和 currentValue 可以是两个值之一。如果在调用 reduce() 时提供了 initialValue,那么 accumulator 将等于 initialValue,currentValue 将等于数组中的第一个值。如果没有提供 initialValue,那么 accumulator 将等于数组中的第一个值,currentValue 将等于第二个。

注意:如果没有提供 initialValue,reduce() 将从索引 1 开始执行回调函数,跳过第一个索引。如果提供了 initialValue,它将从索引 0 开始。

参考MDN


推荐阅读