Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Sogrey opened this issue Sep 11, 2020 · 0 comments
Open

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

Sogrey opened this issue Sep 11, 2020 · 0 comments

Comments

@Sogrey
Copy link
Owner

Sogrey commented Sep 11, 2020

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

第一种使用 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
@Sogrey Sogrey added this to javascript in Web面经题 Sep 11, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Web面经题
javascript
Development

No branches or pull requests

1 participant