JavaScript 如何判断一个对象是否具有给定的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1894792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to determine whether an object has a given property in JavaScript
提问by gnarf
How can I determine whether an object xhas a defined property y, regardless of the value of x.y?
无论 的值如何,如何确定对象是否具有x已定义的属性?yx.y
I'm currently using
我目前正在使用
if (typeof(x.y) !== 'undefined')
but that seems a bit clunky. Is there a better way?
但这似乎有点笨拙。有没有更好的办法?
回答by gnarf
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 inoperator to test for properties that are inherited as well.
您也可以使用in运算符来测试继承的属性。
if ('y' in x) {
// ......
}
回答by CMS
If you want to know if the object physicallycontains the property @gnarf'sanswer using hasOwnPropertywill do the work.
如果您想知道对象物理上是否包含属性@gnarf'sanswer usinghasOwnProperty将完成工作。
If you're want to know if the property exists anywhere, either on the object itself or up in the prototype chain, you can use the inoperator.
如果您想知道该属性是否存在于任何地方,无论是在对象本身上还是在原型链上,您都可以使用in运算符。
if ('prop' in obj) {
// ...
}
Eg.:
例如。:
var obj = {};
'toString' in obj == true; // inherited from Object.prototype
obj.hasOwnProperty('toString') == false; // doesn't contains it physically
回答by nackjicholson
Underscore.js or Lodash
Underscore.js 或 Lodash
if (_.has(x, "y")) ...
:)
:)
回答by jpsimons
You can trim that up a bit like this:
你可以像这样修剪一下:
if ( x.y !== undefined ) ...
回答by jpsimons
One feature of my original code
我的原始代码的一个功能
if ( typeof(x.y) != 'undefined' ) ...
that might be useful in some situations is that it is safe to use whether xexists or not. With either of the methods in gnarf's answer, one should first test for xif there is any doubt if it exists.
在某些情况下可能有用的是,无论是否x存在,使用都是安全的。使用 gnarf 的答案中的任何一种方法,首先应该测试x是否存在任何疑问。
So perhaps all three methods have a place in one's bag of tricks.
因此,也许所有三种方法都在自己的技巧中占有一席之地。
回答by stt
Since question was regarding clunkiness of property checking, and one regular usecase for that being validation of function argument options objects, thought I'd mention a library-free short way of testing existence of multiple properties. Disclaimer: It does require ECMAScript 5 (but IMO anyone still using IE8 deserves a broken web).
由于问题是关于属性检查的笨拙性,以及一个用于验证函数参数选项对象的常规用例,我想我会提到一种测试多个属性是否存在的无库的简短方法。免责声明:它确实需要 ECMAScript 5(但 IMO 任何仍在使用 IE8 的人都应该损坏 Web)。
function f(opts) {
if(!["req1","req2"].every(opts.hasOwnProperty, opts)) {
throw new Error("IllegalArgumentException");
}
alert("ok");
}
f({req1: 123}); // error
f({req1: 123, req2: 456}); // ok
回答by Dome
Why not simply:
为什么不简单:
if (typeof myObject.myProperty == "undefined") alert("myProperty is not defined!");
Or if you expect a specific type:
或者,如果您期望特定类型:
if (typeof myObject.myProperty != "string") alert("myProperty has wrong type or does not exist!");

