gpt4 book ai didi

javascript - 请解释一下这个函数.reduce是如何工作的

转载 作者:行者123 更新时间:2023-11-28 14:15:23 26 4
gpt4 key购买 nike

function countInArray(array, value) {
return array.reduce((n, x) => n + (x === value), 0);
}
console.log(countInArray([1, 2, 3, 4, 4, 4, 3], 4)); // 3

我正在寻找手册中的解释,但在我看来,理解起来非常复杂。

所以我知道 0 是起始总数,并且 x===1 应该等于 1 或 0,具体取决于事实。

我主要对 n 感到困惑,因为我读到 n 是前一个函数的返回值,但一开始就没有前一个函数。

最佳答案

but there's no previous function in the beginning.

确实 - “前一个函数”在开始时并不存在 - 因此 n0 开头,这是您传递给 reduce< 的第二个参数docs给你参数列表:

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

最后一个参数是 initialValue,正如它听起来的那样 - 它是累加器初始值

关于javascript - 请解释一下这个函数.reduce是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57705900/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com