从forEach循环中的第二项开始

dem*_*emo 5 javascript arrays loops typescript

我需要从数组中的第二项开始.为了保存正确的上下文,我需要使用forEach而不是简单的for循环.

我已经完成了下一步:

private convertToRanges(arr: []): any[] {
        const inputArr = arr.slice(),

        if (inputArr.length > 1) {
            let lastIndex = 0;
            inputArr.shift();
            inputArr.forEach(item => {
                ...
            });
        }
        ...
    }
Run Code Online (Sandbox Code Playgroud)

我复制并删除副本中的第一项.

还有另一种方法从第二个项目开始,并确保上下文?

T.J*_*der 14

你不知道从forEach哪里开始,不,但你可以忽略你不想要的电话:

inputArr.forEach((value, index) => {
    if (index < 1) return;
    // Code from here onward will only run for entries that aren't
    // the first entry
});
Run Code Online (Sandbox Code Playgroud)

或者,如果您不担心复制大部分阵列,您可以随时使用slice:

inputArr.slice(1).forEach(value => {
    // ...
});
Run Code Online (Sandbox Code Playgroud)

您还可以定义自己的forEach样式函数,接受起始索引(如果您喜欢),使其不可枚举并仔细选择名称以避免冲突.

也许值得注意的是,既然你正在使用ES2015,那么使用的一些原因forEach会因为块范围而略微消失.for仍然比forEach使用箭头功能更冗长,但是让你以任何你喜欢的方式开始和结束并增加:

for (let i = 1; i < inputArr.length; ++i) {
    // ...`i` and also any `let` or `const` here are scoped to
    // this specific loop iteration...
}
Run Code Online (Sandbox Code Playgroud)

i上面的部分主要是一件好事,但也会产生轻微的性能影响(至少目前为止),因为i必须为每次迭代创建一个新的.然而,并不是说性能影响通常很重要,并且它不会像调用函数那样大forEach.

以上的无端例子:

const inputArr = ['a', 'b', 'c', 'd'];
for (let i = 1; i < inputArr.length; ++i) {
  // A closure to emphasize that each `i` is distinct
  setTimeout(() => {
    console.log("inputArr[" + i + "] = " + inputArr[i]);
  }, 0);
}
Run Code Online (Sandbox Code Playgroud)

(通常我会在那里使用模板文字,但是希望避免给人留下i与之相关的行为.)

  • @DenisGiffeler:仅当您想要改变数组时;OP并没有说出将第一个条目带出的消息。移位也是一种相当昂贵的操作。 (2认同)