admin管理员组文章数量:1308049
I know how to skip first iteration in javascript foreach loop
dataObject.slice(1).forEach((row) => {});
I want to know how to do the same thing using for of loop in javascript, please help me, thanks
for( const row of dataObject )
I know how to skip first iteration in javascript foreach loop
dataObject.slice(1).forEach((row) => {});
I want to know how to do the same thing using for of loop in javascript, please help me, thanks
for( const row of dataObject )
3 Answers
Reset to default 4The same way you're skipping it with forEach
- replace the dataObject
expression with dataObject.slice(1)
.
for( const row of dataObject.slice(1) )
While CertainPerformace's solution is what most people, including me, would go with, it does have a the downside of having to make a temporary array copy, which would be bad when you have huge arrays (but pletely unnoticeable usually).
To prevent copying the array, create a temporary variable to check if it's the first in the loop. The downsides of this is the temporary variable, and the if
check on every iteration could make it slower.
let first = true;
for (const row of dataObject) {
if (first) {
first = false;
continue;
}
// ... rest of script
}
And I would probably just use a traditional incremental for-loop anyways if you want more control over iteration, since forEach
, for-of
, and for-in
are meant to iterate over everything.
If you want to avoid creating a new array (which slice
does), then you can also opt for using one of the iterator helper methods that ECMAScript 2025 introduced: drop:
const data = [1, 2, 3, 4, 5];
for (const row of data.values().drop(1)) console.log(row);
本文标签: nodejsHow to skip first iteration in javascript forof loopStack Overflow
版权声明:本文标题:node.js - How to skip first iteration in javascript for-of loop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741827346a2399723.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论