1、如何判断js对象是否存在某个属性?
- hasOwnProperty()
const obj = {a: 1, b: 2};
obj.hasOwnProperty('a'); // true
obj.hasOwnProperty('c'); // false
- 使用undefined判断
// 该方法存在一个问题,如果属性的值就是undefined的话,该方法不能返回想要的结果
const obj = {a: 1, b: undefined};
obj.a !== undefined; // true
obj.c !== undefined; // false
obj.b !== undefined; // false
- in 关键字
const obj = {a: 1, b: 2};
'a' in obj; // true
'c' in obj; // false
- 点或者方括号
const obj = {a: 1, b: 2};
obj.a // 1
obj.c // undefined
obj['a'] // 1
obj['c'] // undefined
- Object.keys()
const obj = {a: 1, b: 2};
Object.keys(obj).includes('a'); // true
Object.keys(obj).includes('c'); // false