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
可以解决 - 以上方法,每种都有优缺点,有时可能需要结合使用