reduce 方法 (Array) (JavaScript)

array1.reduce(callbackfn, initialValue)

回调函数语法

function callbackfn(previousValue, currentValue, currentIndex, array1)

可使用最多四个参数来声明回调函数。

下表列出了回调函数参数。


第一次调用回调函数

在第一次调用回调函数时,作为参数提供的值取决于reduce方法是否具有initialValue参数。

如果向 reduce 方法提供initialValue

previousValue参数为initialValue

currentValue参数是数组中的第一个元素的值。

如果未提供initialValue

previousValue参数是数组中的第一个元素的值。

currentValue参数是数组中的第二个元素的值。

下面的示例将数组值连接成字符串,各个值用“::”分隔开。由于未向reduce方法提供初始值,第一次调用回调函数时会将“abc”作为previousValue参数并将“def”作为currentValue参数。

JavaScript

// Define the callback function.functionappendCurrent (previousValue, currentValue) {returnpreviousValue +"::"+ currentValue;    }// Create an array.varelements = ["abc","def", 123, 456];// Call the reduce method, which calls the callback function// for each array element.varresult = elements.reduce(appendCurrent);document.write(result);// Output://  abc::def::123::456

下面的示例向数组添加舍入后的值。使用初始值 0 调用reduce方法。

JavaScript

// Define the callback function.functionaddRounded (previousValue, currentValue) {returnpreviousValue + Math.round(currentValue);    }// Create an array.varnumbers = [10.9, 15.4, 0.5];// Call the reduce method, starting with an initial value of 0.varresult = numbers.reduce(addRounded, 0);document.write (result);// Output: 27

下面的示例向数组中添加值。currentIndexarray1参数用于回调函数。

JavaScript

functionaddDigitValue(previousValue, currentDigit, currentIndex, array) {varexponent = (array.length - 1) - currentIndex;vardigitValue = currentDigit * Math.pow(10, exponent);returnpreviousValue + digitValue;    }vardigits = [4, 1, 2, 5];// Determine an integer that is computed from values in the array.varresult = digits.reduce(addDigitValue, 0);document.write (result);// Output: 4125

下面的示例获取一个数组,该数组仅包含另一个数组中的介于 1 和 10 之间值。提供给reduce方法的初始值是一个空数组。

JavaScript

functionProcess(previousArray, currentValue) {// If currentValue is between 1 and 10,// append currentValue to the array.varnextArray;if(currentValue >= 1 && currentValue <= 10)        nextArray = previousArray.concat(currentValue);elsenextArray = previousArray;// If this is not the last call by the reduce method,// the returned array is previousArray on the next call.// If this is the last call by the reduce method, the// returned array is the return value of the reduce method.returnnextArray;}// Create an array.varnumbers = [20, 1, -5, 6, 50, 3];// Call the reduce method, starting with an initial empty array.varemptyArray =newArray();varresultArray = numbers.reduce(Process, emptyArray);document.write("result array="+ resultArray);// Output:// result array=1,6,3

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容