美文网首页js css html
JavaScript Array reduce()

JavaScript Array reduce()

作者: small_zeo | 来源:发表于2022-02-11 16:41 被阅读0次

运用reduce()方法,可以高效简洁的生成想要的数据结构。

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
  • total: 必需。initialValue,或函数先前返回的值。
  • currentValue: 必需。当前元素的值。
  • index: 可选。当前元素的数组索引。
  • arr: 可选。当前元素所属的数组对象
  • initialValue: 可选。作为初始值传递给函数的值。

示例代码:

const dragPositions = [1, 2, 3, 4].reduce((acc, n) => {
  acc[`drag${n}`] = { x: 0, y: 0 }
  return acc
}, {})
image.png

示例中,未指定initialValue初始值,执行了3遍

const func = [1, 2, 3, 4].reduce((total, n) => {
    console.log('total: ', total, 'n: ' + n)
    return total + n
})
// total:  1 n: 2
// total:  3 n: 3
// total:  6 n: 4

示例中,指定initialValue初始值,执行了4遍

const func = [1, 2, 3, 4].reduce((total, n) => {
    console.log('total: ', total, 'n: ' + n)
    return total + n
}, 10)
// total:  10 n: 1
// total:  11 n: 2
// total:  13 n: 3
// total:  16 n: 4

用法定义

reduce() 方法将数组缩减为单个值。
reduce() 方法为数组的每个值(从左到右)执行提供的函数。
函数的返回值存储在累加器中(结果/总计)。
对没有值的数组元素,不执行 reduce() 方法。

注释

reduce() 方法不会改变原始数组。

相关文章

网友评论

    本文标题:JavaScript Array reduce()

    本文链接:https://www.haomeiwen.com/subject/fmxzkrtx.html