JS 配列の reduce メソッド

1. 定義

関数合成の高階関数としてreduce()を使用することができます。

2. 文法

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

3. パラメータの説明

戻り値

4. 使い方

reduce() メソッドはアキュムレータとして関数を受け取り、配列内の各値 (左から右へ) は最初に削減され、最終的に値に計算されます。

5. 注意事項

注:  reduce() は、空の配列に対してコールバック関数を実行しません。

6. 主なアプリケーションは、例を使用して配列配列の合計を説明します。


// 1、没有设置函数的初始迭代值
const array = [1, 2, 3, 4]
const newArr = array.reduce((total, currentValue, index, arr) => {
  console.log(total, currentValue, index, arr);
// 总共迭代三次,打印:
// 1 2 1 (4) [1, 2, 3, 4]
// 3 3 2 (4) [1, 2, 3, 4]
// 6 4 3 (4) [1, 2, 3, 4]
  return total + currentValue
})
console.log(newArr);// 最终求和,打印 10

// 分析:
// 在这里reduce的作用就是对这个数组进行求和,迭代了3次,函数迭代的初始值是1,也就是默
// 认值(数组的第一项),total的值是每次计算后的值。

//-----------------------------------------------------------------------------

//2、设置函数的初始迭代值
const array = [1, 2, 3, 4]
const newArr = array.reduce((total, currentValue, index, arr) => {
  console.log(total, currentValue, index, arr);
// 因为设置可初始值,所以总共迭代四次,打印:
// 5 2 1 (4) [1, 2, 3, 4]
// 6 3 2 (4) [1, 2, 3, 4]
// 8 4 3 (4) [1, 2, 3, 4]
// 11 4 4 (4) [1, 2, 3, 4]
  return total + currentValue
},5)
console.log(newArr);// 最终求和,打印 15
// 分析:
// 这里添加了一个初始的迭代值,也就是让total从5开始计算,可以看到这里迭代了4次,结果也加上了
// 初始值。

7. 一般的な例 

1. 加算、乗算など

const arr = [1, 2, 3, 4, 5]
console.log(arr.reduce((a, b) => a + b))//15
console.log(arr.reduce((a, b) => a * b))//120
console.log(arr.reduce((a, b) => a - b))//-13
console.log(arr.reduce((a, b) => a / b))//0.008333333333333333

2.配列内の各要素の出現回数を計算する

const array = ['name', 'age', 'long', 'short', 'long', 'name', 'name']
const arrResult = array.reduce((total, cur) => {
console.log(total, cur)
   if (cur in total) {
    total[cur]++
  } else {
    total[cur] = 1
  }
  return total
}, {})
console.log(arrResult)
//结果:
// {name: 3, age: 1, long: 2, short: 1},name出现三次,age出现1次,long出现两次,short出现一次

// 分析:
// 1、由于设置了迭代初始值,total的第一个值是一个空对象,此时cur为name,然后进行判断,发现在pre没
// 有name属性,所以就将name对应的属性值赋为1;
// 2、后面没有重复的是一样的道理,如果碰到重复值,就会将该属性值加1,这样就能计算元素重复的次了。

3.配列内の重複要素を削除する

const array = ['name', 'age', 'long', 'short', 'long', 'name', 'name']
const arrResult = array .reduce((pre,cur) =>{
    if(!pre.includes(cur)){
        pre.push(cur)
    }
    return pre;
},[])

console.log(arrResult)//结果:["name", "age", "long", "short"]

// 分析:
// 这里主要是借助迭代功能实现数组的扩展,判断当前元素是否已经添加到数组中,如果不存在就从尾部加,
// 这个方法在去重方法中应该算比较简单高效的。

4. オブジェクトのプロパティを合計します。

const array= [
    {
        name: 'xiaoming',
        age: 18
    },{
        name: 'xiaohong',
        age: 17
    },{
        name: 'xiaogang',
        age: 19
    }
]

const result = array.reduce((a,b) =>{
    a += b.age;
    return a;
},0)

console.log(result)//结果:54
// 分析:
//  这里主要就是利用reduce第一个参数是迭代,可以通过初始化这个参数的数据类型,达到想实现的效果。

おすすめ

転載: blog.csdn.net/a15220216758/article/details/125029602