Home>Article>Web Front-end> How to find the sum of odd numbers in an array in es6
Method: 1. Use forEach() to traverse the array and pass the array elements to the callback function one by one. The syntax is "arr.forEach(function(v){});"; 2. In the function, judge Whether the passed in elements are odd numbers, if so, add them and sum them up, the syntax is "if(v%2!=0){sum =v;}".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
es6 method to find the sum of odd numbers in an array
##Implementation idea:
Implementation method:
1. Use forEach() to traverse the array
The forEach() method is used to call each element of the array. and pass the element to the callback function.arr.forEach(function(value) { ... });
2. In the callback function, you can perform parity judgment and summation.
You only need to judge whether the array elements passed into the callback function can be divisible by 2. Just add elements that are not divisible.if(value%2!=0){ sum += value; }Implementation code:
var arr = [1,2,3,4,5,6,7,8,9], sum = 0; arr.forEach(function(value) { if(value%2!=0){ sum += value; } }); console.log("数组的奇数和为:"+sum);[Related recommendations:
javascript video tutorial,web front-end]
The above is the detailed content of How to find the sum of odd numbers in an array in es6. For more information, please follow other related articles on the PHP Chinese website!