## 提到循环,我们首先想到的就是for循环,在js中可不止这一种循环方法哦,还有for…of、forEach和for…in等多种实现循环的方法,它们之间的联系与区别是什么?
1 for
for遍历数组与对象数组 用于大多数据结构遍历 自行获取数据结构key, value等 可以使用break,continue语句
// for:遍历数组
var arr = ['红色', '黑色', '蓝色','白色']
for (var i = 0; i < arr.length; i++) {
console.log(i);
console.log(arr[i]);
}
//对象数组
var arr = [
{ name: 'jean', sex: '女', age: 18}
]
for (var i = 0; i < arr.length; i++) {
console.log(i);
console.log(arr[i]);
}
2 forEach
forEach遍历数组,用于遍历数组, Set和Map数据结构 可以通过回调函数参数传入value,key和自身,同时可以改变this指向(回调函数为非箭头函数时) 不能使用break和continue语句
//forEach遍历数组数组
var arr = ['红色', '黑色', '蓝色','白色'];
arr.forEach(function (value, index) {
console.log(index); //索引
console.log(value); //值
})
//forEach遍历对象数组
var arr = [
{ name: 'jean', sex: '女', age: 18}
]
arr.forEach(function (value, index) {
console.log(index); //索引
console.log(value); //值
})
//使用forEach方法遍历set成员
const s = new Set([1,2,3]);
s.forEach(function (value, key, set) {
console.log(value, key, set);
});
console.log(s);
// 使用forEach方法遍历map成员
const m = new Map([
['color', 'red'],
['backgroundColor', 'blue'],
['fontSize', '40px']
]);
m.forEach(function (value, key, set) {
console.log(value, key, set);
});
3 for … in
// for…in:遍历数组索引、对象的属性 //只能获得key, 没有value // 可以使用break和continue语句
const arr = ['红色', '黑色', '蓝色','白色'];
for (const [index, value] in arr) {
console.log(index, value);
}
console.log(arr);
4 for of
// for of 用于遍历数组字符串,Set,Map等,不能直接遍历对象 // 默认获得value,但可以通过keys(),values(),entries()获得对应可遍历对象 // 可以使用break和continue语句
const arr = ['红色', '黑色', '蓝色','白色'];
for (const [index, value] of arr.entries()) {
console.log(index, value);
}
console.log(arr);
// for of 可以使用break和continue语句
const arr = ['红色', '黑色', '蓝色','白色'];
for (const value of arr) {
if (value ==='黑色'){
break;
}
console.log(value);
}
console.log(arr);
const arr = ['红色', '黑色', '蓝色','白色'];
for (const value of arr) {
if (value ==='黑色'){
continue;
}
console.log(value);
}
console.log(arr);