美文网首页Web前端之路程序员让前端飞
js 判断对象中是否有某属性的方法

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

作者: 嘻哈章鱼小丸子 | 来源:发表于2021-02-02 16:21 被阅读0次
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可以解决
  • 以上方法,每种都有优缺点,有时可能需要结合使用

相关文章

网友评论

    本文标题:js 判断对象中是否有某属性的方法

    本文链接:https://www.haomeiwen.com/subject/mtpytltx.html