Lax_Sam
Lax_Sam

Reputation: 1139

Can forEach be used to increment or decrement by more than 1 in Javascript?

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

Answers (3)

Jack Bashford
Jack Bashford

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

Nina Scholz
Nina Scholz

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

Amadan
Amadan

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

Related Questions