簡體   English   中英

如何使用箭頭函數在 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));
};

另外,如果有人能告訴我使用速記語句來做到這一點的最短方法,我很樂意學習!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM