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

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

问题描述

此外,这是一个风格问题还是一个功能性问题?是优先考虑还是更好?我试图了解for-of的目的。



通常我使用,

  let iterable = [10,20,30]; 

iterable.forEach((val)=> {
console.log(val);
})

但我看到这种新语法可用。

  let iterable = [10,20,30]; 

for(let iterable){
console.log(value);
}

可以提供一个最佳用例示例当一个人应该使用它时会发光吗?

解决方案

这是一个非常有趣的问题,已在许多其他网站上讨论过。我将发布我读过的基础知识。


ForEach 完全属于皇室的数组。 forEach方法引入了Array对象的原型继承的谱系!毋庸置疑,forEach子句仅适用于那些数组结构,即数组。该方法基本上遍历数组的元素并执行回调函数[基本上是一些可执行函数/有趣活动]。








for-of循环对于JS世界来说是新的,并且包含超级大国! Voilaaaaaaa! for-of循环创建一个循环遍历可迭代成员对象的循环。该列表是广泛的,例如





  • 数组

  • 地图

  • 设置

  • 字符串

  • TypedArray

  • 其他W3C班级




你需要知道这个坏孩子男孩在2015年诞生了ES6。因此,它提供了充分的使用灵活性







性能



在性能方面,的快于 forEach 可在此处找到结果



forEach
$的慢24% b $ b




更新



如我所提到的,W3C规范中还有其他几个可迭代类,如FileList。以上。在最近的W3C草案中(当ES6发布时),像HTMLCollection和NodeList这样的集合现在也实现了forEach(),而不仅仅是Array。 通过 @Patrick Roberts



< hr>

来源链接:




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.

Usually I use,

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?

解决方案

This is a very intersting question which has been discussed in many other sites. I'll post the basics of what i have read.

ForEach exclusively belong to the royal family of Arrays. The forEach method was introduced with lineage to the prototypal inheritance of Array object! Needless to say, the forEach clause works only with those data structure which are Arrays. The method basically iterates over the elements of the array and executes a callback function [basically some executable function/ fun activity].


The for-of loop is adequately new to the JS world and packs in super-powers! Voilaaaaaaa! The for-of loop creates a loop iterating over iterable member objects. The list is an extensive one such as

  • Array
  • Map
  • Set
  • String
  • TypedArray
  • Other W3C classes

You need to know that this bad-ass boy emerged with the birth of ES6 in 2015. So, it offers plenty of flexibility in usage


Performance

In performance, for...of is faster than forEach. Results can be found here

forEach is 24% slower than for...of


Update

There are several other iterable classes in the W3C specification, like FileList, as I mentioned above. And in recent drafts of W3C (around when ES6 was released), collections like HTMLCollection and NodeList now implement forEach() as well, not just Array anymore. By @Patrick Roberts


Source Links:

这篇关于迭代数组时是否应该使用for-of或forEach?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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