Home  >  Article  >  Web Front-end  >  How to find the sum of odd numbers in an array in es6

How to find the sum of odd numbers in an array in es6

青灯夜游
青灯夜游Original
2022-05-23 19:26:141616browse

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;}".

How to find the sum of odd numbers in an array in es6

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:

  • Traverse the array

  • Determine whether the array elements are odd

  • Add the odd elements

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);

How to find the sum of odd numbers in an array in es6

[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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn