IDC

JS中循环遍历数组方式总结

作者:admin 2021-06-09 我要评论

本文比较并总结遍历数组的四种方式: for 循环: for(let index = 0 ;index someArray.length ;index++){ const elem = someArray [index]; // } for-in 循环: ...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

本文比较并总结遍历数组的四种方式:

  • for 循环:
    1. for (let index=0; index < someArray.length; index++) { 
    2.   const elem = someArray[index]; 
    3.   // ··· 
  • for-in 循环:
    1. for (const key in someArray) { 
    2.   console.log(key); 
  • 数组方法 .forEach():
    1. someArray.forEach((elem, index) => { 
    2.   console.log(elem, index); 
    3. }); 
  • for-of 循环:
    1. for (const elem of someArray) { 
    2.   console.log(elem); 

for-of 通常是最佳选择。我们会明白原因。

for循环 [ES1]

JavaScript 中的 for 循环很古老,它在 ECMAScript 1 中就已经存在了。for 循环记录 arr 每个元素的索引和值:

  1. const arr = ['a', 'b', 'c']; 
  2. arr.prop = 'property value'
  3.  
  4. for (let index=0; index < arr.length; index++) { 
  5.   const elem = arr[index]; 
  6.   console.log(index, elem); 
  7.  
  8. // Output: 
  9. // 0, 'a' 
  10. // 1, 'b' 
  11. // 2, 'c' 

for 循环的优缺点是什么?

  • 它用途广泛,但是当我们要遍历数组时也很麻烦。
  • 如果我们不想从第一个数组元素开始循环时它仍然很有用,用其他的循环机制很难做到这一点。

for-in循环 [ES1]

for-in 循环与 for 循环一样古老,同样在 ECMAScript 1中就存在了。下面的代码用 for-in 循环输出 arr 的 key:

  1. const arr = ['a', 'b', 'c']; 
  2. arr.prop = 'property value'
  3.  
  4. for (const key in arr) { 
  5.   console.log(key); 
  6.  
  7. // Output: 
  8. // '0' 
  9. // '1' 
  10. // '2' 
  11. // 'prop' 

for-in 不是循环遍历数组的好方法:

  • 它访问的是属性键,而不是值。
  • 作为属性键,数组元素的索引是字符串,而不是数字。
  • 它访问的是所有可枚举的属性键(自己的和继承的),而不仅仅是 Array 元素的那些。

for-in 访问继承属性的实际用途是:遍历对象的所有可枚举属性。

数组方法.forEach()[ES5]

鉴于 for 和 for-in 都不特别适合在数组上循环,因此在 ECMAScript 5 中引入了一个辅助方法:Array.prototype.forEach():

  1. const arr = ['a', 'b', 'c']; 
  2. arr.prop = 'property value'
  3.  
  4. arr.forEach((elem, index) => { 
  5.   console.log(elem, index); 
  6. }); 
  7.  
  8. // Output: 
  9. // 'a', 0 
  10. // 'b', 1 
  11. // 'c', 2 

这种方法确实很方便:它使我们无需执行大量操作就能够可访问数组元素和索引。如果用箭头函数(在ES6中引入)的话,在语法上会更加优雅。

.forEach() 的主要缺点是:

  • 不能在它的循环体中使用 await。
  • 不能提前退出 .forEach() 循环。而在 for 循环中可以使用 break。

中止 .forEach() 的解决方法

如果想要中止 .forEach() 之类的循环,有一种解决方法:.some() 还会循环遍历所有数组元素,并在其回调返回真值时停止。

  1. const arr = ['red', 'green', 'blue']; 
  2. arr.some((elem, index) => { 
  3.   if (index >= 2) { 
  4.     return true; // 中止循环 
  5.   } 
  6.   console.log(elem); 
  7.   //此回调隐式返回 `undefined`,这 
  8.   //是一个伪值。 因此,循环继续。 
  9. }); 
  10.  
  11. // Output: 
  12. // 'red' 
  13. // 'green' 

可以说这是对 .some() 的滥用,与 for-of 和 break 比起来,要理解这段代码并不容易。

for-of循环 [ES6]for-of

循环在 ECMAScript 6 开始支持:

  1. const arr = ['a', 'b', 'c']; 
  2. arr.prop = 'property value'
  3.  
  4. for (const elem of arr) { 
  5.   console.log(elem); 
  6. // Output: 
  7. // 'a' 
  8. // 'b' 
  9. // 'c' 

for-of 在循环遍历数组时非常有效:

  • 用来遍历数组元素。
  • 可以使用 await,如果有需要,可以轻松地迁移到 for-await-of。
  • 甚至可以将 break 和 continue 用于外部作用域。

for-of 和可迭代对象

for-of 不仅可以遍历数组,还可以遍历可迭代对象,例如遍历 Map:

  1. const myMap = new Map() 
  2.   .set(false, 'no') 
  3.   .set(true, 'yes') 
  4. for (const [key, value] of myMap) { 
  5.   console.log(key, value); 
  6.  
  7. // Output: 
  8. // false, 'no' 
  9. // true, 'yes' 

遍历 myMap 会生成 [键,值] 对,可以通过对其进行解构来直接访问每一对数据。

for-of 和数组索引

数组方法 .entries() 返回一个可迭代的 [index,value] 对。如果使用 for-of并使用此方法进行解构,可以很方便地访问数组索引:

  1. const arr = ['chocolate', 'vanilla', 'strawberry']; 
  2.  
  3. for (const [index, elem] of arr.entries()) { 
  4.   console.log(index, elem); 
  5. // Output: 
  6. // 0, 'chocolate' 
  7. // 1, 'vanilla' 
  8. // 2, 'strawberry' 

总结

for-of 循环的的可用性比 for,for-in 和 .forEach() 更好。

通常四种循环机制之间的性能差异应该是无关紧要。如果你要做一些运算量很大的事,还是切换到 WebAssembly 更好一些。


本文转载自网络,原文链接:http://mp.weixin.qq.com/s?__biz=MzI3NzIzMDY0NA==&mid=2247497896&idx=1&sn=f0e113b3dd5dbde94278de2e2b6ddd4b&chksm=eb6bddf3dc1c54e56d65b98cc0e7c4b6b064f1a60ae4b8fbfdedc357be7564ea3935ac195b2e&mpshare=1&s

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • 【活动回顾】Edge X Kubernetes,探索

    【活动回顾】Edge X Kubernetes,探索

  • 云端赛车-Amazon DeepRacer 的前世今生

    云端赛车-Amazon DeepRacer 的前世今生

  • 云原生时代,企业多活容灾体系构建思路

    云原生时代,企业多活容灾体系构建思路

  • 如何帮用户管好云账本?阿里云数据库助

    如何帮用户管好云账本?阿里云数据库助

腾讯云代理商
海外云服务器