跳过forEach循环的第一次迭代

3

如何在forEach循环中跳过第一次迭代?我的forEach循环正常工作,但我需要从第二项开始,完全忽略第一项。我正在使用ES6。

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

我想我可以做类似这样的事情:
cars.skip(1).forEach(car => {...do something});

3
你可以使用slice:https://www.w3schools.com/jsref/jsref_slice_array.asp - Johan Maes
我明白了!谢谢,先将其设置为新对象,然后将其用作循环的输入。再次感谢。 - luke jon
只需使用常规的 for 循环,并将索引从 0 开始改为从 1 开始。 .forEach() 已经过时了。 - jfriend00
5个回答

9

你需要检查索引并在该值上使用return,这是你所需要的。在你的情况下,你需要跳过零索引(0),以下是代码:

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

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

此代码将显示'bmw'和'maybach'。

没有必要执行 return false,因为 .forEach() 不会关注返回值。只需要执行 if (index === 0) return; 即可。 - jfriend00

5

2

这应该是一个相对简单的单项测试 - 您的“执行某些操作”函数可以根据需要设置/读取外部变量。

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

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


0

要不考虑使用 切片 循环?

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

0

由于forEach循环中没有计数变量可用,您需要手动创建一个变量来计数。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接