const arr = [1, 2, 3];
// for循环: 能够使用break, continue, return控制循环; 通过下标间接访问元素
for (let index = 0; index < arr.length; index++) {
const element = arr[index];
console.log(element);
}
// forEach: 不能使用break, continue控制循环(函数的本意就是要遍历每个元素), 但是可以使用return效果相当于continue(不建议在该函数中使用)
arr.forEach((value, index) => {
if (value == 2) {
return false;
}
// console.log(value);
});
// for-in: 最好用于遍历对象, 支持break和continue, return终止循环
for (const key in arr) {
if (arr.hasOwnProperty(key)) {
const element = arr[key];
// if(element === 2){
// break;
// }
console.log(element);
}
}
// for-of: 专门为数组设计的遍历方法,直接遍历其属性,支持break和continue, return终止循环
// 也可以遍历具有Symbol.iterator接口的任何数据结构
for (const item of arr) {
if(item === 2){
continue;
}
// console.log(item);
}
const iterator = arr[Symbol.iterator]();
while(true){
const next = iterator.next();
if(next.done){
break;
}
// console.log(next.value);
}
// every: 变相遍历数组
arr.every((value, index) => {
// console.log(index, value);
return true; // 返回真值继续下次循环等同于continue,返回假值结束循环等同于break
});
JS循环汇总
点赞
收藏