简体   繁体   English

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

[英]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.我只是做了一个编码挑战,我知道如何使用没有箭头函数的 forEach 循环使用经典的 if-else 语句来解决它。

Now I wonder how can I achieve this using ES6 within the forEach loop?现在我想知道如何在 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);

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.我已经学会了如何为 forEach 循环创建箭头函数,但我不知道如何添加 if-else 语句。

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!另外,如果有人能告诉我使用速记语句来做到这一点的最短方法,我很乐意学习!

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

Shortest possible way最短的路

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

Another way to do it would be另一种方法是

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

The easiest way would be to just change the function(element) { to (element) => { :最简单的方法是将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);

If you really needed a concise body without the { , you can use && instead, but this is hard to read (I definitely wouldn't recommend it):如果你真的需要一个没有{的简洁正文,你可以使用&&代替,但这很难阅读(我绝对不会推荐它):

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

But I'd prefer using .filter followed by forEach instead:但我更喜欢使用.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);

No need to do it in if-else condition, you can do it using filter function that will do magic for you please follow the below following code,无需在 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)

Live Run : https://jsbin.com/qavejof/edit?js,console实时运行: https : //jsbin.com/qavejof/edit?js,console

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM