Print

js如何检查对象中是否存在某个属性?


作者: 文章来源:

本文原地址:https://www.mimiwuqi.com/webqianduan/197438.html

检查对象中是否存在属性有三种方法。

第一种使用 in 操作符号:

const o = { 
  "prop" : "bwahahah",
  "prop2" : "hweasa"
};

console.log("prop" in o); // true
console.log("prop1" in o); // false

第二种使用 hasOwnProperty 方法,hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性(也就是,是否有指定的键)。

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

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

console.log(o["prop"]); // "bwahahah"
console.log(o["prop1"]); // undefined

更多 建站教程 请访问 https://www.mimiwuqi.com/webqianduan/