javascript - 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了?
解决方案
没有。的初始值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
推荐阅读
- r - 获取列表中 df 的特定列的名称
- typescript - 如何在 NestJS 中配置 TypeORM 以使用 postgres 复制?
- javascript - Django3:动态生成可以在 HTML 页面中使用的 js
- python - 编码分类特征?
- python - Scrapy 的多个请求
- paypal - 如何使用 PayPal 订阅多个定期付款计划?
- python - 使用 for 循环与使用 .copy() 或 [:] 复制列表
- c++ - 删除的功能,不能将一条记录重写为另一条记录,对象
- xamarin.forms - 无法在 UWP 应用程序中发现蓝牙设备,但在 WPF 应用程序中工作
- react-native - 如何在 React Native 中的身份验证状态更改时更改路由