javascript - 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.
Now I wonder how can I achieve this using ES6 within the forEach loop?
// 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.
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);
}
});
};
最短的可能方式
const oddProduct = arr => {
arr.forEach(element => element % 2 === 0 && console.log(element))
};
另一种方法是
const oddProduct = arr => arr.forEach(e => e%2 && console.log(e))
推荐阅读
- node.js - 导出的函数返回未定义的 NodeJS
- android - 使用 Multipart Retrofit 和 java Rest api 上传 Android 文件
- r - 在R中有效地重命名连续列组
- javascript - Reactjs Drawer 没有在每个页面上打开
- rpgle - 伸肌 M 和 R 如何在 RPGLE 上使用 CALLP?
- wordpress - 海洋WP页面顶部的白条(Elementor)
- r - 使用 ggplot2 制作带有偏移基线的条形图
- javascript - 从打字稿中的地图中删除数组值
- javascript - Reach/Router - 主要组件中经过身份验证的路由与受保护的路由
- python - 进行一步预测