Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize the summation of arrays by es6

Shulou Source: shulou.com Published: 2022-05-31 20:33:52 09月10日 Update

In this article Xiaobian for you to introduce in detail "es6 how to achieve array summation", the content is detailed, the steps are clear, the details are handled properly, I hope this "es6 how to achieve array summation" article can help you solve your doubts, following the editor's ideas slowly in-depth, together to learn new knowledge.

Es6 method to achieve array summation: 1, using the reduce () method, syntax "arr.reduce (function (pjournal c) {sum=p+c;});"; 2, using the forEach () method, syntax "arr.forEach (function (v) {sum+=v})".

The operating environment of this tutorial: windows7 system, ECMAScript version 6, Dell G3 computer.

In es6, you can use the new array traversal methods reduce () and forEach () to sum the array. Let's take a look at the details.

Method 1: use the reduce () method

Reduce can traverse the array, let the front and back items of the array do some calculation, then return its value, and continue the calculation without changing the original array, returning the final result of the calculation; if no initial value is given, the traversal starts with the second term of the array.

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.

Example: use the reduce () method for array summation

Var arr = [11, 12, 13], sum= 0 position arr.reduce (function (pre,curr) {sum=pre+curr;return sum;}); console.log (sum)

Method 2: use the forEach () method

The forEach () method invokes each element of the array and passes the element to the callback function.

In the callback function, you can do a sum operation to add up all the elements of the array passed in.

Example: accumulate array values

Var arr = [1,2,3], sum = 0posiarr.forEach (function (value) {sum + = value;}); console.log (sum)

After reading this, the article "how to realize the summation of arrays in es6" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, please follow the industry information channel.

Tags: Arrays methods elements functions articles content examples grammar appropriateness ideas tutorials new knowledge more steps environment computer knowledge knowledge points articles systems Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker NVidia MySQL Linux Shulou Information