如何使用箭头功能在forEach循环中使用Modulo?

问题描述 投票:0回答:3

我只是做一个编码挑战,我知道如何使用不带箭头功能的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));
};

此外,如果有人可以使用速记语句告诉我最简单的方法,我很乐意学习!

javascript ecmascript-6 arrow-functions
3个回答
0
投票

最简单的方法是将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);

0
投票

无需在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


0
投票
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))

0
投票

最短的可能(并且比传统的n%2===0快一点)将是二进制n&1,如果我们在这里谈论的是奇/偶校验:

const src = [2,3,6,7,8],
      logEvens = arr => arr.forEach(n => !(n&1) && console.log(n))
      
logEvens(src)      
.as-console-wrapper {min-height: 100%}

尽管,对于大多数相似(但实际)的用例,您可能希望使用其他高阶方法,例如Array.prototype.filter()

Array.prototype.filter()
const src=[2,3,6,7,8],
      filtered = src.filter(n => !(n&1))
      
console.log(filtered)      
© www.soinside.com 2019 - 2024. All rights reserved.