js数组遍历 for、foreach、for in、for of

for 循环:

for (let i=0; i < array.length; i++) {
    const elem = array[i];
    // ···
}

for-in 循环:

循环输出 array 的 key

const array = [a, b, c];
array.prop = value;

for (const key in array) {
    console.log(key);
}
 
// Output:
// 0
// 1
// 2
// prop
    它访问的是属性键,而不是值。 作为属性键,数组元素的索引是字符串,而不是数字。 它访问的是所有可枚举的属性键(自己的和继承的),而不仅仅是 Array 元素的那些。

数组方法 .forEach():

array.forEach((elem, index) => {
    console.log(elem, index);
});
    不能在它的循环体中使用 await。 不能提前退出 .forEach() 循环。而在 for 循环中可以使用 break。

for-of 循环:

ECMAScript 6 开始支持

const array = [a, b, c];
array.prop = value;

for (const elem of array) {
    console.log(elem);
}

// Output:
// a
// b
// c
    用来遍历数组元素。 可以使用 await 如果有需要,可以轻松地迁移到 for-await-of。 可以将 break 和 continue 用于外部作用域。
经验分享 程序员 微信小程序 职场和发展