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