【问题标题】:How to use Modulo inside of a forEach loop using arrow function?如何使用箭头函数在 forEach 循环中使用模数?
【发布时间】:2019-12-19 08:03:23
【问题描述】:

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

现在我想知道如何在 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


    【解决方案1】:

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

    【讨论】:

    • 谢谢!这回答了我的问题!所以我必须使用另一个 => 来启动下一个功能,明白了!
    【解决方案2】:

    在 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

    【讨论】:

      【解决方案3】:
      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))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-23
        • 1970-01-01
        相关资源
        最近更新 更多