0
点赞
收藏
分享

微信扫一扫

js 判断对象中是否有某属性的方法

编程练习生J 2021-09-28 阅读 62
1. .[]
const obj = {a:1, b:2, c:3,d:undefined};
obj.d //undefined
obj.e //undefined
obj.toString  //ƒ toString() { [native code] }

缺点:不能用在属性值为 undefined 的场景

2. in
const obj = {a:1, b:2, c:3,d:undefined};
'd' in obj //true
'e' in obj //false
'toString' in obj //true

缺点:无法区分自身和原型链上的属性

3. Reflect.has
const obj = {a:1, b:2, c:3,d:undefined};
Reflect.has(obj,'d') //true
Reflect.has(obj,'e') //false
Reflect.has(obj,'toString') //true

缺点:无法区分自身和原型链上的属性,同方法二

4. hasOwnProperty
const obj = {a:1, b:2, c:3,d:undefined};
obj.hasOwnProperty('d') //true
obj.hasOwnProperty('e') //false
obj.hasOwnProperty('toString') //false

缺点:只能判断自身属性

总结
  • 方法1的缺点方法2,3可以解决,方法2,3的缺点方法4可以解决
  • 以上方法,每种都有优缺点,有时可能需要结合使用
举报

相关推荐

0 条评论