检查对象中是否存在属性有三种方法。
第一种使用in操作符号:
const o = {
"prop" : "bwahahah",
"prop2" : "hweasa"
};
console. log("prop" in o); // true
console. Log("propl" in o); // false
第二种使用hasOwnProperty方法,hasOwnProperty()方法会返回一个布尔值,指示对象自 身属性中是否具有指定的属性(也就是,是否有指定的键)。
console. log(o. hasOwnProperty("prop2")); // true
console. log(o. hasOwnProperty("propl")); // false
第三种使用括号符号obj[Bprop"]0如果属性存在,它将返回该属性的值,否则将返回 undefined。
console. log(o["prop"]); // "bwahahah" console. log(o["propl"]); // undefined

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.