判断对象中是否存在特定属性

93 阅读1分钟

第一种使用 in 操作符号:

const obj = { 
  "prop" : "xxx",
  "prop2" : "xxx1"
};
console.log("prop" in obj); // true
console.log("prop1" in obj); // false

第二种使用 hasOwnProperty 方法,hasOwnProperty() 方法会返回一个布尔值。

console.log(obj.hasOwnProperty("prop2")); // true
console.log(obj.hasOwnProperty("prop1")); // false

第三种使用括号符号obj["prop"]。如果属性存在,它将返回该属性的值,否则将返回undefined。

console.log(obj["prop"]); // "xxx"
console.log(obj["prop1"]); // undefined