本文介绍了迭代数组时是否应该使用for-of或forEach?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 此外,这是一个风格问题还是一个功能性问题?是优先考虑还是更好?我试图了解for-of的目的。 通常我使用, let iterable = [10,20,30]; iterable.forEach((val)=> { console.log(val); }) 但我看到这种新语法可用。 let iterable = [10,20,30]; for(let iterable){ console.log(value); } 可以提供一个最佳用例示例当一个人应该使用它时会发光吗?解决方案这是一个非常有趣的问题,已在许多其他网站上讨论过。我将发布我读过的基础知识。 数组 地图 设置 字符串 TypedArray 其他W3C班级 性能 在性能方面,的快于 forEach 。 可在此处找到结果 forEach 比 $的慢24% b $ b 更新 如我所提到的,W3C规范中还有其他几个可迭代类,如FileList。以上。在最近的W3C草案中(当ES6发布时),像HTMLCollection和NodeList这样的集合现在也实现了forEach(),而不仅仅是Array。 通过 @Patrick Roberts 来源链接: https://codeburst.io/foreach-vs-for-of-vs-for- in-tug-of-d8f935396648 https://www.reddit.com/r/javascript/comments/4spd5b/forof_vs_foreach/ 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.ArrayMapSetStringTypedArrayOther W3C classesPerformanceIn performance, for...of is faster than forEach. Results can be found hereforEach is 24% slower than for...ofUpdateThere 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 RobertsSource Links:https://codeburst.io/foreach-vs-for-of-vs-for-in-tug-of-for-d8f935396648https://www.reddit.com/r/javascript/comments/4spd5b/forof_vs_foreach/ 这篇关于迭代数组时是否应该使用for-of或forEach?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-23 02:50
查看更多