Reputation: 1139
Can forEach
function be used to loop over an array by more than 1? For eg using for
loop we do it like this:
for(var i=0; i<my_arr.length; i+=2) {
//code
}
Upvotes: 1
Views: 3190
Reputation: 44145
You can just return
from an incorrect index:
const my_arr = [1, 2, 3, 4];
my_arr.forEach((e, i) => {
if (!(i % 2)) return;
console.log(e);
});
Upvotes: 2
Reputation: 386868
No, you can not omit some indices without explicit returning in the callback.
array.forEach((value, index) => {
if (index % 2) return;
// your code
});
Upvotes: 4
Reputation: 198526
No. However, it is easy to skip elements by their index:
let my_arr = [1, 2, 3, 4, 5];
my_arr.forEach((e, i, a) => {
if (i % 2 != 0) return;
console.log(e);
});
Upvotes: 3