js如何检查对象中是否存在某个属性?
检查对象中是否存在属性有三种方法。
第一种使用 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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » js如何检查对象中是否存在某个属性?
码云笔记 » js如何检查对象中是否存在某个属性?