循环语法比较及使用场景(for、forEach、for...in、for...of)
chenpeng 2020-11-30 ES6基础
# 1.for
for(let i = 0; i < array.length; i++){
console.log(array[i])
}
1
2
3
2
3
这种方法遍历数组的下标是 Number 类型
# 2.forEach
array.forEach(item => console.log(item))
1
forEach 的缺点:无法中途跳出循环,break、continue、return 都不能生效
# 3.for...in
for...in 可以遍历能够通过对象访问的,可枚举的属性,其中包括实例中的属性,也包括原型中的属性
const arr = [1,2,3];
for(let k in arr){
console.log(k);
}
1
2
3
4
2
3
4
for...in 实际是为可枚举对象而设计的,用来遍历带有字符串的 key 的对象
遍历数组时,输出的数组下标是字符串类型,会将数组原型中的属性也返回,所以不推荐用 for...in 遍历数组
# 4.for...of
const arr = [1,2,3];
for(let v of arr){
console.log(v);
}
1
2
3
4
2
3
4
for...of 用来遍历具备 Iterator 接口的数据结构,返回数组中的值
比传统的 for 循环简洁,同时弥补了 for...in 短板,可以搭配 break、continue、return 一起使用