forEach、for in、for of 的区别

  • forEach:更多用来循环数组的,但是不能通过return、break终止循环
var arr = [11, 22, 33, 24]
arr.forEach(element => {
  if (element == 22) return
  console.log(element)   // 11 33 24
})
  • for of:通常用来遍历数组的,循环得到的是value
var arr = [11, 22, 33, 24]
for (const key of arr) {
  console.log(key)  // 11 22 33 24
}
  • for in:通常用来遍历对象的,循环得到的是key,会遍历原型链上可枚举的属性
    ( Object.hasOwnProperty()方法判断某个属性是否是该对象自身的属性,而不是原型链上的 )
// 遍历对象
let obj = {a: '1', b: '2', c: '3', d: '4'}
for (let o in obj) {
    console.log(o)    //遍历的实际上是对象的属性名称 a,b,c,d
    console.log(obj[o])  //这个才是属性对应的值1,2,3,4
}

// =====================================================================
1、Object.hasOwnProperty.call(obj, key)
var obj = {
  name: 'hehe',
  age: 12
}
Object.prototype.gender = '女'
for (const key in obj) {
  if (Object.hasOwnProperty.call(obj, key)) {
    // 判断是不是自身上的属性,不包含原型链上的;返回布尔值
    const element = obj[key]
    console.log(element) // hehe 12
  }
}

// =====================================================================
2、Object.hasOwnProperty(key):
Object.prototype.gender = '女'
var person = {
  name: 'tebu',
  age: 12
}
for (var key in person) {
  if (person.hasOwnProperty(key)) {
    console.log(key, person[key])
  }
}
// name tebu
// age 12
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值