首页 > 解决方案 > How to use Modulo inside of a forEach loop using arrow function?

问题描述

I just do a coding challenge and I know how to solve it with a classic if-else statement using a forEach loop without arrow functions.

Now I wonder how can I achieve this using ES6 within the forEach loop?

// Create a function that returns the product of all odd integers in an array.
const odds = [ 2, 3, 6, 7, 8 ];
const oddProduct = (arr) => {
    arr.forEach(function(element) {
        if (element % 2 === 0) {
            console.log(element);
        }
    });
};

oddProduct(odds);

I already learned how to create an arrow function for the forEach loop, but I have no clue how to add in the if-else statement.

const oddProduct = (arr) => {
    arr.forEach((element) => console.log(element));
};

Also, if someone could tell me the shortest possible way to do this using shorthand statements, I'd be happy to learn!

标签: javascriptecmascript-6arrow-functions

解决方案


const oddProduct = (arr) => {
    arr.forEach((element) => {
       if (element % 2 === 0) {
         console.log(element);
       }
    });
};

最短的可能方式

const oddProduct = arr => {
      arr.forEach(element => element % 2 === 0 && console.log(element))
 };

另一种方法是

const oddProduct = arr => arr.forEach(e => e%2 && console.log(e))

推荐阅读