使... of跳过循环的最后一个元素

时间:2018-07-24 16:27:15

标签: javascript arrays for-loop for-of-loop

如果存在使用for...of进行迭代的二维数组,跳过最后一个元素的最佳方法是什么?

例如,有一个数组arr,通常的方法是:

for(const subArray of arr) { ... }

跳过可以在循环之前使用的最后一个元素:arr.slice(0, -1);可以正常工作,但会删除应避免的数据。

有没有办法使它跳过最后一个元素而不会丢失数据?

2 个答案:

答案 0 :(得分:1)

slice()不会更改数组,但会返回一个新数组(与splice()不同,它会改变数组),因此可以安全使用:

for (const subArray of arr.slice(0, -1)) { ... }

答案 1 :(得分:0)

您还可以使用生成器:

curl -sSL https://github.com/jjqq2013/bash-scripts/raw/master/common/relpath | bash -s -- /a/b/c/d/e /a/b/CC/DD/EE

source <(curl -sSL https://github.com/jjqq2013/bash-scripts/raw/master/common/relpath)
relpath /a/b/c/d/e /a/b/CC/DD/EE

wget https://github.com/jjqq2013/bash-scripts/raw/master/common/relpath
chmod +x relpath
./relpath /a/b/c/d/e /a/b/CC/DD/EE

可用作:

function* skipLast(array, numOfEntries = 1) {
  for(let i = 0; i < array.length - numOfEntries; i++)
     yield array[i];
}