迭代数组时应该使用 for-of 还是 forEach ? [英] Should one use for-of or forEach when iterating through an array?
问题描述
另外,这是一个风格问题还是一个功能问题?这是一个偏好问题还是一个更好的问题?我试图理解 for-of 的目的.
Also, is this a style question or a functional question? Is it a matter of preference or is one better? I'm trying to understand the purpose of for-of.
我通常使用,
let iterable = [10, 20, 30];
iterable.forEach((val) => {
console.log(val);
})
但我发现这种新语法是可用的.
But I see that this new syntax is available.
let iterable = [10, 20, 30];
for (let value of iterable) {
console.log(value);
}
能否提供一个最佳用例示例,说明何时应该使用它?
Can one provide an example of a best use case for for-of that might illuminate when one should use it?
推荐答案
我建议在 ES6 中始终使用 for ... of
.
I recommend to always use for … of
in ES6.
- 它适用于任何iterable
- 支持循环体中的各种控制流,如
continue
、break
、return
、yield
和await
.
- It works on any iterable
- It supports all kinds of control flow in the loop body, like
continue
,break
,return
,yield
andawait
.
我个人也觉得它更具可读性,但这归结为偏好.有些人认为 forEach
是一种更函数式的风格,但这是错误的 - 它没有结果价值,而且只是为了产生副作用,所以看起来命令式的循环更适合这个目的.
Also I personally find it more readable, but that comes down to preference. Some people think forEach
is a more functional style, but that's wrong - it has no result value and is all about doing side effects, so an imperative-looking loop fits that purpose better.
性能不是问题,在现代引擎中,所有循环样式都是等效的.
这篇关于迭代数组时应该使用 for-of 还是 forEach ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!