for in,for of 和 forEach的对比

对比总结

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值