JavaScript 如何使用Array.prototype.reduce()方法

JavaScript 如何使用Array.prototype.reduce()方法

Array.prototype.reduce()方法用于在数组中执行用户提供的回调函数,并从数组中返回单个值。它从给定数组的最左元素遍历到最右元素。

Array.prototype.reduce()可以通过两种方式进行调用。

  • 回调函数:首先声明该函数,然后在数组上调用执行。

语法:

array.reduce( myFunction, initialValue )
JavaScript
  • 行内回调函数: 参数被传递到 reduce() 方法内的函数中,同时也传入要执行的数组。

语法:

reduce(function(returnValue, currentValue, currentIndex, array){ 
... }, initialValue)
JavaScript

参数:

  • array: 我们要遍历的数组。
  • myFunction: 将在数组上执行的回调函数。它接受四个参数:
    • returnValue: 它是回调函数之前调用的返回值。在第一次调用时,它采用initialValue的值,否则采用数组的第一个元素的值,即array[0]。
    • currentValue: 它是回调函数当前执行的元素的当前值。在第一次调用时,如果指定了initialValue,它是数组的第一个元素,否则它是array[1],即数组的第二个元素。
    • currentIndex: 它是“currentValue”元素的索引值。如果指定了initialValue,则为0,否则为1。
    • array: 我们需要遍历的数组。
  • initialValue: 这是一个可选参数,如果指定了,则将其初始化为 returnValue ,然后从索引0开始对数组的其他元素执行。

示例 1: 在该示例中,我们将看到在Javascript中使用回调函数的Array.prototype.reduce()方法的基本用法。

const array = [10, 18, 30, 41, 60];
const myReducer = (returnValue,
    currentValue) => returnValue + currentValue;
 
// 10 + 18 + 30 + 41 + 60
console.log(array.reduce(myReducer));
// expected output: 159
 
// initialValue = 20
// 20 + 10 + 18 + 30 + 41 + 60
console.log(array.reduce(myReducer, 20));
    // expected output: 179
JavaScript

输出:

159
179
JavaScript

示例2: 在这个示例中,我们将看到Javascript中使用Array.prototype.reduce()方法的示例。

const array1 = [1, 2, 3, 4, 5];
 
// Calculating sum of squares
const myReducer = (returnValue, currentValue) =>
    returnValue + currentValue * currentValue;
 
// 1 + 4 + 9 + 16 + 25
console.log(array1.reduce(myReducer));
// expected output: 55
 
// initialValue = 6
// 36 + 1 + 4 + 9 + 16 + 25
console.log(array1.reduce(myReducer, 36));
    // expected output: 91
JavaScript

输出:

55
91
JavaScript

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册