admin 管理员组文章数量: 1086019
I can either do,
var arr = [];
arr.forEach(function(i) {
i;
});
for (var i = 0, length = arr.length; i < length; ++i) {
arr[i];
}
When should I use one over the other, is there performance differences?
I can either do,
var arr = [];
arr.forEach(function(i) {
i;
});
for (var i = 0, length = arr.length; i < length; ++i) {
arr[i];
}
When should I use one over the other, is there performance differences?
Share Improve this question asked Jun 4, 2013 at 18:02 user2251919user2251919 6752 gold badges11 silver badges23 bronze badges 6-
2
forEach
is slower, but it creates a scope for each iteration, which you manually have to do with a normalfor
(if you need one)...and also lets you set the value ofthis
in the callback (with its second parameter). It's also not supported in all browsers: kangax.github.io/es5-pat-table/#Array.prototype.forEach .forEach
also doesn't loop over empty items. Read more here: developer.mozilla/en-US/docs/Web/JavaScript/Reference/… - it includes a polyfill for browsers that don't support it – Ian Commented Jun 4, 2013 at 18:05 - This partially answers your question: stackoverflow./questions/9329446/… – vasanth Commented Jun 4, 2013 at 18:05
- 1 To answer the performance question, create a performance test on jsperf. with 50,000 values in your array. Or executing 50,000 loops. – LarsH Commented Jun 4, 2013 at 18:05
-
forEach
is ECMAScript 5 -> patibility – Moritz Roessler Commented Jun 4, 2013 at 18:06 - 1 @Tim I see that one snippet has live output while the other has not - that might change the time required for the iteration. You know - they are lies, damn lies, and benchmarks. :) – Zsolt Szilagyi Commented Jun 4, 2013 at 18:22
1 Answer
Reset to default 10You use foreach whenever :
- your array is associtive or has gaps, i.e. you cannot reach every element by an incremented number (1,2,5, 'x', -7)
- you need to iterate in exactly the same order as they appear in the array. (e.g. 2,1,3)
- you want to be sure not the get into an endless loop
The last point is the main difference: foreach works on a copy, so even if you alter the elements, the array remains intact and can be iterated without defects.
That copy makes foreach somewhat slower than for, since it has to copy data. Keep in mind that some old or rare browsers don´t supports foreach, but they do support "for". Unless your array is really big (10.000 + items), ignore the speed difference. It´s in the milliseconds.
You use for whenever
- you want an easy way to aler the array you are moving on
- you want specific sequences, e.g. for ($i=100; $i < 1000; $i += 5) resulting in 100, 105, 110...
本文标签: javascriptWhen should I use forEachStack Overflow
版权声明:本文标题:javascript - When should I use forEach? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1743998793a2516065.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论