Javascript javascript中forEach和for循环的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25994909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between forEach and for loop in javascript
提问by sachinjain024
I am wondering: Is there any significant difference between forEachand forloop in JavaScript.
我想知道:JavaScript 中的forEach和for循环之间有什么显着区别。
Consider this example:
考虑这个例子:
var myArray = [1,2,3,4];
myArray.forEach(function(value) {
console.log(value);
});
for (var i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
Here is part of my research:
这是我研究的一部分:
- Performance: According to JsPerf: forEach is little slower than for loop.
- Usability: There is no way we can break/return from the callback in case of forEach loop.
- 性能:根据JsPerf:forEach 比 for 循环慢一点。
- 可用性:在 forEach 循环的情况下,我们无法从回调中中断/返回。
For example: You want to find out if a number is prime or not. I think using for loop is much more easier than using forEach loop to do this.
例如:您想确定一个数是否为素数。我认为使用 for 循环比使用 forEach 循环要容易得多。
- Readability:Using for loop makes code more readable than having forEach in code.
- Browser compatibility: forEach is Not supported in IE < 9 So that introduces some shim in our code.
- 可读性:使用 for 循环使代码比在代码中使用 forEach 更具可读性。
- 浏览器兼容性:在 IE < 9 中不支持 forEach 因此在我们的代码中引入了一些垫片。
My questions are:
我的问题是:
- What are the advantages of forEach over for loop ?
- In what scenarios, forEach is more preferable.
- Why did even it come into JavaScript ? Why was it needed at all ?
- forEach 相对于 for 循环的优势是什么?
- 在什么场景下,forEach 更可取。
- 为什么它会出现在 JavaScript 中?为什么需要它?
采纳答案by Lea Rosema
forEachis a method on the Arrayprototype. It iterates through each element of an array and passes it to a callback function.
forEach是Array原型上的一个方法。它遍历数组的每个元素并将其传递给回调函数。
So basically, forEachis a shorthand method for the use-case "pass each element of an arrayto a function". Here is a common example where I think Array.forEachis quite useful, compared to a forloop:
所以基本上,forEach是用例的速记方法“将 an 的每个元素传递array给 a function”。这是一个我认为Array.forEach与for循环相比非常有用的常见示例:
// shortcut for document.querySelectorAll
function $$(expr, con) {
return Array.prototype.slice.call((con || document).querySelectorAll(expr));
}
// hide an element
function hide(el) {
el.style.display = 'none';
}
// hide all divs via forEach
$$('div').forEach(hide);
// hide all divs via for
for (var divs = $$('div'), i = 0; i < divs.length; i++) {
hide(divs[i])
}
As you can see, the readability of the forEach statement is improved compared to a forloop.
如您所见,与for循环相比,forEach 语句的可读性得到了提高。
On the other hand, a forstatement is more flexible: it does not necessarily involve an array. The performance of a normal forloop is slightly better, because there is no function call for each element involved. Despite of this, it is recommended to avoid forloops when it can be written as a forEachstatement.
另一方面,for语句更灵活:它不一定涉及数组。普通for循环的性能稍好一些,因为没有对涉及的每个元素进行函数调用。尽管如此,建议for在可以将其编写为forEach语句时避免循环。
回答by naivists
In a forEachloop you don't control the way you iterate over the array. The classic forloop allows you to choose the iteration algorithm as you want (i++; i--; i+=2*i, etc).
在forEach循环中,您无法控制迭代数组的方式。经典for循环允许您根据需要选择迭代算法(i++; i--;i+=2*i等)。
However, a forEachloop is much easier to use - you don't need to mess with all the icounting, finding the array[i]object -- JS does it for you.
然而,forEach循环使用起来要容易得多——你不需要搞乱所有的i计数,找到array[i]对象——JS 会为你做这件事。
回答by Phil H
>> sparseArray = [1, 2, , 4];
>> sparseArray.forEach(console.log, console);
1 0 [1, 2, 3: 4]
2 1 [1, 2, 3: 4]
4 3 [1, 2, 3: 4]
>> for(var i = 0; i < sparseArray.length; ++i) { console.log(sparseArray[i]) };
1
2
undefined
4
forEachis a recent addition to make expressive list-comprehension style possible in javascript. Here you can see that forEachskips elements that were never set, but the best you can do with a forloop is to check for undefinedor null, both of which can be set as values and picked up by forEach. Unless you expect missing values, forEachis equivalent to forloops, but note that you cannot stop early, for which you need every.
forEach是最近添加的,使 JavaScript 中的表达列表理解风格成为可能。在这里您可以看到forEach跳过从未设置过的元素,但是您可以使用for循环做的最好的事情是检查undefinedor null,这两者都可以设置为值并由 拾取forEach。除非您期望缺少值,否则forEach等效于for循环,但请注意,您不能提前停止,为此您需要every.
回答by jso1919
In simple terms, according to the below article, and research, it seems that the main differences are:
简单来说,根据下面的文章和研究,主要区别似乎是:
For Loop
For循环
- It's one of the original ways of iterating over arrays
- It's faster
- You could
breakout of it using this keyword - In my opinion its mainly used for calculations with integers (numbers)
- The parameters are
(iterator, counter, incrementor)
- 这是迭代数组的原始方法之一
- 它更快
- 你可以
break使用这个关键字 - 在我看来它主要用于计算整数(数字)
- 参数是
(iterator, counter, incrementor)
ForEach Loop
ForEach 循环
- It's a newer way with less code to iterate over arrays
- Easier to read
- Lets you keep variable within the scope
- Lower chance of accidental errors with the
i <= >= etc..... - The parameters are
(iterator, Index of item, entire array)
- 这是一种更新的方法,用更少的代码来迭代数组
- 更容易阅读
- 让你在范围内保持变量
- 降低意外错误的可能性
i <= >= etc..... - 参数是
(iterator, Index of item, entire array)
回答by Foz
Here is a difference between forEach and for loop in JavaScript.
这是 JavaScript 中 forEach 和 for 循环之间的区别。
Performance wise, I prefer the for loop over the forEach loop. This is just one of some issues I have come across with the forEach loop.
在性能方面,我更喜欢 for 循环而不是 forEach 循环。这只是我在 forEach 循环中遇到的一些问题之一。
let abc = [1,2,3]
abc.forEach((e) => {
delete e;
})
console.log(abc) //Array(3) [ 1, 2, 3 ]
for (let i = 0; i < abc.length; i++) {
delete abc[i];
}
console.log(abc) //Array(3) [ <3 empty slots> ]

