最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Skip first iteration during forEach loop - Stack Overflow

programmeradmin1浏览0评论

How can I skip the first iteration in a forEach loop? I've got my forEach loop working as expected but I need to start on the second item totally ignoring the first item. I'm using ES6.

cars.forEach(car => {...do something});

I thought I could maybe do something like

cars.skip(1).forEach(car => {...do something});

How can I skip the first iteration in a forEach loop? I've got my forEach loop working as expected but I need to start on the second item totally ignoring the first item. I'm using ES6.

cars.forEach(car => {...do something});

I thought I could maybe do something like

cars.skip(1).forEach(car => {...do something});
Share Improve this question asked Aug 14, 2020 at 5:26 luke jonluke jon 2011 gold badge2 silver badges10 bronze badges 3
  • 3 You could use slice: w3schools.com/jsref/jsref_slice_array.asp – Johan Maes Commented Aug 14, 2020 at 5:29
  • I got it! Thank you, set as new object before then use that for my input into the loop. Thanks again – luke jon Commented Aug 14, 2020 at 5:35
  • Just use a regular for loop and start the index at 1 instead of 0. .forEach() is so yesterday. – jfriend00 Commented Aug 14, 2020 at 8:42
Add a comment  | 

6 Answers 6

Reset to default 11

you need to check index, and use return on that value, what you need. In your case you need to skip zero index (0), here is code

const cars = ['audi', 'bmw', 'maybach']

cars.forEach((car, index) => {
  if (index === 0) return;
  console.log(car)
});

this code will show 'bmw' and 'maybach'

Writing out my comment as an answer:

cars.slice(1).forEach(car => { do something });

MDN reference to slice method: https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Should be a fairly simple one-item test - your 'do something' function can set/read an external variable as required.

let myArray = [1,2,3,4,5];

let firstItem = true;
myArray.forEach(item => {
  if (firstItem != true){
    console.log(item);
  } else {
    firstItem = false;
  }
});

since there is counting variable available in forEach loop, you manually make one to count it.

let count = 0;
let skipVal = 0;
cars.forEach(car => {
count++;
if (count != skipVal){
...do something
}
});

How about a sliced for loop?

const s=['car','bike','plane']
for(each of s.slice(1))console.log(each)

As of ECMAScript 2025, you can call drop on an iterable, so you can now do:

const cars = ["Honda", "Mercedez", "Tesla", "Peugeot"];

cars.values().drop(1).forEach(car => console.log(car));

发布评论

评论列表(0)

  1. 暂无评论