Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use JavaScript's reduce ()

Shulou Source: shulou.com Published: 2022-06-02 12:56:29 10月04日 Update

This article mainly explains "how to use JavaScript's reduce ()". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use JavaScript's reduce ()".

Case study

Calculate the sum of the added elements of the array:

Varnumbers= [65,44,12,4]

FunctiongetSum (total,num) {

Returntotal+num

}

FunctionmyFunction (item) {

Document.getElementById ("demo") [xss_clean] = numbers.reduce (getSum)

}

Output result:

one hundred and twenty five

Definition and usage

The reduce () method takes a function as an accumulator, and each value in the array (from left to right) starts to shrink and eventually evaluates to a value.

Reduce () can be used as a higher-order function for the compose of a function.

Note: reduce () does not execute callback functions for empty arrays.

Browser support

The numbers in the table represent the first browser version number that supports the method.

Method

Reduce () Yes 9.03.04 10.5

Grammar.

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

Parameters.

Parameter description

Function (total,currentValue,index,arr) is required. The function used to execute each array element.

Function parameters:

Parameter description

Total is required. The initial value, or the return value after the calculation is finished.

CurrentValue is required. Current element

CurrentIndex is optional. Index of the current element

Arr is optional. The array object to which the current element belongs.

InitialValue is optional. The initial value passed to the function

Technical details

Return value: returns the calculation result

JavaScript version: ECMAScript3

Thank you for your reading, the above is the content of "how to use JavaScript's reduce ()". After the study of this article, I believe you have a deeper understanding of how to use JavaScript's reduce (), and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Functions elements arrays parameters methods learning content browsers versions results support browsing instances objects that is ideas summation situation ownership technology Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Docker NVidia Shulou Technology MySQL