从forEach循环中的第二个项目开始 [英] Start from second item in forEach loop

查看:322
本文介绍了从forEach循环中的第二个项目开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to start from second item in array. In order to save correct context I need to use forEach instead of simple for loop.

我已经用另一种方式完成了:

I've done it in next way :

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

        if (inputArr.length > 1) {
            let lastIndex = 0;
            inputArr.shift();
            inputArr.forEach(item => {
                ...
            });
        }
        ...
    }

我进行复印并删除复印件中的第一项.

I make copy and remove first item in copy.

还有另一种方法可以从第二个项目开始并确定上下文吗?

Is there another way to start from second item and be context sure?

推荐答案

您不能告诉forEach从哪里开始,不可以,但是您可以忽略不需要的呼叫:

You can't tell forEach where to start, no, but you can ignore the calls you don't want:

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

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

Or if you're not worried about copying most of the array, you can always use slice:

inputArr.slice(1).forEach(value => {
    // ...
});

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

You could also define your own forEach-style function accepting a starting index, if you liked, making it non-enumerable and choosing the name carefully to avoid conflicts.

也许还值得注意的是,由于您使用的是ES2015,因此使用forEach的某些原因由于块作用域而略微消失了. for仍然比带有箭头功能的forEach更为冗长,但是可以让您根据自己的喜好开始,结束和递增:

It's also perhaps worth noting that since you're using ES2015, some of the reasons for using forEach go away a bit thanks to block scope. for is still a bit more verbose than forEach with an arrow function, but lets you start and end and increment by whatever you like:

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

上面有关i的部分主要是一件好事,但对性能(至少到目前为止)也有轻微影响,因为必须为每次迭代创建一个新的i.但这并不是说性能影响通常根本不重要,它不会像调用a'la forEach函数那样大.

The part about i above is primarily a good thing, but also has a slight performance impact (at least for now) since a new i has to be created for each iteration. Not that that performance impact usually matters at all, though, and it won't be as big as calling a function a'la 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);
}

(通常,我会在此处使用模板文字,但要避免给印象留下与之相关的行为.)

这篇关于从forEach循环中的第二个项目开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆