迭代数组时应该使用 for-of 还是 forEach ? [英] Should one use for-of or forEach when iterating through an array?

查看:18
本文介绍了迭代数组时应该使用 for-of 还是 forEach ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另外,这是一个风格问题还是一个功能问题?这是一个偏好问题还是一个更好的问题?我试图理解 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
  • 支持循环体中的各种控制流,如continuebreakreturnyieldawait.
  • It works on any iterable
  • It supports all kinds of control flow in the loop body, like continue, break, return, yield and await.

我个人也觉得它更具可读性,但这归结为偏好.有些人认为 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屋!

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