JS中循环遍历数组的四种方式分析
for (let index=0; index < someArray.length; index++) { const elem = someArray[index]; // ··· }
for-in 循环:
for (const key in someArray) { console.log(key); }
数组方法 .forEach():
someArray.forEach((elem, index) => { console.log(elem, index); });
for-of 循环:
for (const elem of someArray) { console.log(elem); }
for-of 通常是最佳选择。我们会明白原因。
for循环 [ES1]
JavaScript 中的 for 循环很古老,它在 ECMAScript 1 中就已经存在了。for 循环记录 arr 每个元素的索引和值:
const arr = ['a', 'b', 'c']; arr.prop = 'property value';
for (let index=0; index < arr.length; index++) { const elem = arr[index]; console.log(index, elem); }
// Output: // 0, 'a' // 1, 'b' // 2, 'c'
for 循环的优缺点是什么?
它用途广泛,但是当我们要遍历数组时也很麻烦。
如果我们不想从第一个数组元素开始循环时它仍然很有用,用其他的循环机制很难做到这一点。
for-in循环 [ES1]
for-in 循环与 for 循环一样古老,同样在 ECMAScript 1中就存在了。下面的代码用 for-in 循环输出 arr 的 key:
const arr = ['a', 'b', 'c']; arr.prop = 'property value';
for (const key in arr) { console.log(key); }
// Output: // '0' // '1' // '2' // 'prop'
for-in 不是循环遍历数组的好方法:
它访问的是属性键,而不是值。
作为属性键,数组元素的索引是字符串,而不是数字。
它访问的是所有可枚举的属性键(自己的和继承的),而不仅仅是 Array 元素的那些。
for-in 访问继承属性的实际用途是:遍历对象的所有可枚举属性。
数组方法.forEach()[ES5]
鉴于 for 和 for-in 都不特别适合在数组上循环,因此在 ECMAScript 5 中引入了一个辅助方法:Array.prototype.forEach():
const arr = ['a', 'b', 'c']; arr.prop = 'property value';
arr.forEach((elem, index) => { console.log(elem, index); });
// Output: // 'a', 0 // 'b', 1 // 'c', 2
这种方法确实很方便:它使我们无需执行大量操作就能够可访问数组元素和索引。如果用箭头函数(在ES6中引入)的话,在语法上会更加优雅。
.forEach() 的主要缺点是:
不能在它的循环体中使用 await。
不能提前退出 .forEach() 循环。而在 for 循环中可以使用 break。
中止 .forEach() 的解决方法
如果想要中止 .forEach() 之类的循环,有一种解决方法:.some() 还会循环遍历所有数组元素,并在其回调返回真值时停止。
const arr = ['red', 'green', 'blue']; arr.some((elem, index) => { if (index >= 2) { return true; // 中止循环 } console.log(elem); //此回调隐式返回 `undefined`,这 //是一个伪值。 因此,循环继续。 });
// Output: // 'red' // 'green'
可以说这是对 .some() 的滥用,与 for-of 和 break 比起来,要理解这段代码并不容易。
for-of循环 [ES6]
for-of 循环在 ECMAScript 6 开始支持:
const arr = ['a', 'b', 'c']; arr.prop = 'property value';
for (const elem of arr) { (编辑:焦作站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |