如何使用箭头函数在 forEach 循环中使用 Modulo?

How to use Modulo inside of a forEach loop using arrow function?

我刚刚完成了一个编码挑战,我知道如何使用没有箭头函数的 forEach 循环使用经典的 if-else 语句来解决它。

现在我想知道如何在 forEach 循环中使用 ES6 来实现这一点?

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

我已经学会了如何为 forEach 循环创建箭头函数,但我不知道如何在 if-else 语句中添加。

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

此外,如果有人能告诉我使用 shorthand 语句执行此操作的最短方法,我将很乐意学习!

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

最简单的方法是将 function(element) { 更改为 (element) => {:

const odds = [ 2, 3, 6, 7, 8 ];
const oddProduct = (arr) => {
    arr.forEach((element) => {
        if (element % 2 === 0) {
            console.log(element);
        }
    });
};

oddProduct(odds);

如果你确实需要没有{的简洁正文,你可以使用&&代替,但这很难读(我绝对不会'推荐它):

const odds = [ 2, 3, 6, 7, 8 ];
const oddProduct = (arr) => {
    arr.forEach(element => element % 2 === 0 && console.log(element))
};

oddProduct(odds);

但我更喜欢使用 .filter,然后是 forEach

const odds = [ 2, 3, 6, 7, 8 ];
const oddProduct = (arr) => {
  arr
    .filter(element => element % 2 === 0)
    .forEach(element => console.log(element));
};

oddProduct(odds);

无需在 if-else 条件下执行此操作,您可以使用过滤器函数来执行此操作,它会为您带来神奇效果,请遵循以下代码,

const odds = [ 2, 3, 6, 7, 8 ];

const evenValue = odds.filter((value, index, self) => {
  return self.indexOf(value) % 2 == 0;
});

console.log(evenValue)

直播 运行 : https://jsbin.com/qavejof/edit?js,console