Home > Article > Web Front-end > Examples to explain six methods of summing array elements in JavaScript
JavaScript is an essential part of front-end development. Arrays are an important part of JavaScript. Do you know how to sum array elements? This article uses examples to share with you six methods of summing JS arrays. It has certain reference value and interested friends can take a look.
Take the array arr = [1,2,3,4,5,1] as an example to find the sum of the elements in the array. The specific method is as follows:
Method 1. The for loop method
The for method can loop through the array to sum the array elements
var arr = [1,2,3,4,5,1]; function getSumfor(arr){ var sum = 0; for(var i = 0;i<arr.length;i++){ sum += arr[i]; } return sum ; } console.log(getSumfor(arr));
The calculation result is as shown in the figure:
Method 2, every method
Every() can detect whether each element in the array meets the conditions and thus sum up
var arr = [1,2,3,4,5,1]; function getSumevery(arr){ var sum = 0; arr.forEach( function(item){ sum += item ; }); return sum ; } console.log(getSumevery(arr));
Method 3, some method
The some method can be used to detect whether the elements in the array meet the specified conditions, thereby summing the array elements
var arr = [1,2,3,4,5,1]; function getSumSome(arr){ var sum = 0; arr.some( function(item){ sum += item ; return false; }); return sum ; } console.log(getSumSome(arr));
Method 4, map method
The map() method can process each element of the array through the specified function, and then return the processed array.
var arr = [1,2,3,4,5,1]; function getSumMap(arr){ var sum = 0; arr.map( function(item){ sum += item ; }); return sum ; } console.log(getSumMap(arr));
Method 5, filter method
The filter() method can detect the elements in the array and return an array of all elements that meet the conditions.
var arr = [1,2,3,4,5,1]; function getSumFilter(arr){ var sum = 0; arr.filter( function(item){ sum += item ; }); return sum ; } console.log(getSumFilter(arr));
Method 6, foreach method
forEach can call each element in the array
var arr = [1,2,3,4,5,1]; function getSumForEach(arr){ var sum = 0; arr.forEach( function(item){ sum += item ; }); return sum ; } console.log(getSumForEach(arr));
The above introduces you to the array element search in JavaScript The six methods of sum are for, every, some, map, filter, and foreach. If you have unclear knowledge, you can refer to JavaScript Video Tutorial. I hope this article will be helpful to you. !
The above is the detailed content of Examples to explain six methods of summing array elements in JavaScript. For more information, please follow other related articles on the PHP Chinese website!