互联网技术 · 2024年3月31日 0

JS中遍历数组的四种方法总结

这篇文章主要给大家总结介绍了关于JS中循环遍历数组的四种方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

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

foR 循环:

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) {
console.log(eleM);
}
// output:
// a
// b
// c

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

用来遍历数组元素。

可以使用 awAIt

如果有需要,可以轻松地迁移到 foR-awAIt-of。

甚至可以将 break 和 continue 用于外部作用域。

foR-of 和可迭代对象

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

const MyMap = new Map()
.set(FAlse, no)
.set(tRue, yes)
;
foR (const [key, value] of MyMap) {
console.log(key, value);
}

// output:
// FAlse, no
// tRue, yes

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

foR-of 和数组索引

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

const aRR = [chocolate, vanilla, stRawbeRRy];

foR (const [index, eleM] of aRR.entRies()) {
console.log(index, eleM);
}
// output:
// 0, chocolate
// 1, vanilla
// 2, stRawbeRRy

总结

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

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

到此这篇关于JS中循环遍历数组的四种方式总结的文章就介绍到这了