Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

javascript - 如何确定对象在JavaScript中是否具有给定属性(How to determine whether an object has a given property in JavaScript)

How can I determine whether an object x has a defined property y , regardless of the value of xy ?

(如何确定对象x是否具有已定义的属性y ,而不管xy的值是多少?)

I'm currently using

(我正在使用)

if (typeof(x.y) !== 'undefined')

but that seems a bit clunky.

(但这似乎有点笨拙。)

Is there a better way?

(有没有更好的办法?)

  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Object has property:(对象有属性:)

If you are testing for properties that are on the object itself (not a part of its prototype chain) you can use .hasOwnProperty() :

(如果要测试对象本身的属性(不是其原型链的一部分),可以使用.hasOwnProperty() :)

if (x.hasOwnProperty('y')) { 
  // ......
}

Object or its prototype has a property:(对象或其原??型具有以下属性:)

You can use the in operator to test for properties that are inherited as well.

(您可以使用in运算符来测试继承的属性。)

if ('y' in x) {
  // ......
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...