Mat*_*vic 3 javascript arrays reduce max
为什么第二个示例返回NaN,而第一个示例有效?
const numbers = [ 1, 2, 3 ]
console.log('passing arrow funciton', numbers.reduce((l, r) => Math.max(l, r)) ) // 3
console.log('passing bound function', numbers.reduce(Math.max.bind(Math)) ) // NaNRun Code Online (Sandbox Code Playgroud)
为了给你一些上下文,reduce函数需要一个Callback参数.此外,回调需要两个参数,即累积和当前元素(您也可以左右调用它们等).有更多参数但它们是可选的.
我试图模仿reduce函数,这个例子就像魅力一样
const numbers = [1, 2, 3]
const reduce = (array, func) => {
let largest = 0
array.forEach
(
(number, i, a) =>
a[i + 1]
? largest = func(number, a[i + 1])
: console.log('done')
)
return largest
}
console.log( 'mock reduce', reduce(numbers, Math.max.bind(Math)) ) // 3Run Code Online (Sandbox Code Playgroud)
回调.reduce()函数传递了4个参数:累加器,当前元素,索引和整个数组.它NaN来自尝试将数组本身转换为数字.
因此,在第一次调用回调时,.max()将传递1, 2, 1, [1, 2, 3].那将会回归NaN,然后就会NaN一路走来.除了NaN来自数组的问题之外,如果你有一个包含大量小数或负数的长数组,索引值也可能会降低结果的准确性.
请注意,我在这里描述的是.reduce()传递给所提供的回调函数的参数列表,而不是.reduce()自身的参数.该.reduce()函数总是将所有四个参数传递给回调,但JavaScript的本质是函数可以忽略多余的参数.这正是你的第一个例子所做的.
| 归档时间: |
|
| 查看次数: |
188 次 |
| 最近记录: |