对比总结
for…in…特点
遍历对象返回对象的key值,遍历数组返回数组的下标。(适合遍历对象)
-
for … in 会遍历原型上的属性值
-
可以中断( 可以与 break、continue和return 配合使用)
for…in…的缺点:会遍历原型链上的所有属性(解决方法:hasOwnProperty())
for…of…特点
- 不能遍历对象,遍历数组会返回数组的值
- 可以中断( 可以与 break、continue和return 配合使用)
- 总结:适合遍历数组,以及其他可迭代对象
forEach特点
- 不能遍历对象,遍历数组会返回数组的值
- 不能中断
详细比较
1)可枚举对象
使用for…in…
const Person = {
name: '张三',
age: 18
}
for (let i in Person){
console.log(i) //name age
}
for…in…是对对象的key值进行循环
使用for…of…
const Person = {
name : '张三',
age : 18
}
for (let i of Person){
console.log(i) // Person is not iterable
}
for…of…不能对对象进行循环遍历
使用forEach
const Person = {
name: '张三',
age: 18
}
Person.forEach(i => console.log(i)) //Person.forEach is not a function
forEach不能对对象进行循环遍历
2)可枚举数组
使用for…in…
const arr = ['a', 'b', 'c']
for (let i in arr){
console.log(i) // 0 1 2
}
for…in…会输出索引值
使用for…of…
const arr = ['a', 'b', 'c']
for (let i of arr){
console.log(i) // a b c
}
for…of…会输出数组值
使用forEach
const arr = ['a', 'b', 'c']
arr.forEach( i => console.log(i)) // a b c
forEach会输出数组值
3)可枚举数组的原型对象
使用for…in…
const arr = [7, 12, 20]
arr.name = '数组'
Array.prototype.sayHi = function () {
console.log('Hi~')
}
Array.prototype.str = 'Hello'
for (let i in arr){
console.log(i) // 0 1 2 name sayHi str
}
for…in…不仅返回数组下标,而且会返回数组的原型对象属性值以及数组对象本身属性值。
解决方法:hasOwnProperty()
for (let i in arr){
if (arr.hasOwnProperty(i)){
console.log(i) // 0 1 2 name
}
}
使用for…of…
const arr = [7, 12, 20]
arr.name = '数组'
Array.prototype.sayHi = function () {
console.log('Hi~')
}
Array.prototype.str = 'Hello'
for (let i of arr){
console.log(i) // 7 12 20
}
使用forEach
const arr = [7, 12, 20]
arr.name = '数组'
Array.prototype.sayHi = function () {
console.log('Hi~')
}
Array.prototype.str = 'Hello'
arr.forEach((value) => {
console.log(value) // 7 12 20
})
4)能否中断
forEach使用break不能中断循环
const arr = [1, 3, 5, 7]
arr.forEach((value) => {
console.log(value) // 1 3 5 7
if (value === 5) return false
})
输出结果是1,3,5,7
从结果可以看出,return false没有执行,他会一直运行到底
使用for…in…
const arr = [1, 3, 5, 7]
for (let i in arr){
console.log(arr[i]) // 1 3 5
if (arr[i] === 5) break
}
for…in…可以使用break
使用for…of…
const arr = [1, 3, 5, 7]
for (let i of arr){
console.log(i) // 1 3 5
if (i === 5) break
}
for…of…可以使用break
参考文章:https://blog.csdn.net/baidu_33438652/article/details/107266260