JavaScript 遍历数组
shell
# for 循环
for # 最原始、性能最好,唯二可中断数组遍历
for…of # 直接取值,唯二可中断数组遍历
for…in # 不推荐遍历数组,会遍历原型属性,顺序不稳定。
# 非 for 循环、
while
do…while
# 数组自带方法
forEach # 遍历执行,无返回值
map
filter
find
findIndex
some
every
reduce
reduceRight案例
const arr = [1, 2, 3];
for 循环
最原始、性能最好,可中断
js
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}for…of
直接取值
js
for (const item of arr) {
console.log(item);
}for…in
不推荐遍历数组,会遍历到原型、索引是字符串,容易出问题
js
for (const index in arr) {
console.log(arr[index]);
}while 循环
js
let i = 0;
while (i < arr.length) {
console.log(arr[i]);
i++;
}do…while 循环
不推荐遍历数组,会遍历到原型、索引是字符串,容易出问题
js
let i = 0;
do {
console.log(arr[i]);
i++;
} while (i < arr.length);