简体   繁体   English

如何访问javaScript对象属性NAME(不值VALUE)

[英]How to access javaScript object property NAME not VALUE

I have a an object 我有一个对象
me = { name: "Mo", age: 28, } And I want to see if this object has the property "height" for example. me = { name: "Mo", age: 28, }我想看看该对象是否具有例如“ height”属性。 (which it doesn't) How can i do this? (没有)我该怎么做? So for example if it has the property "height" I can give it a value of "5,7". 因此,例如,如果它具有属性“ height”,则可以将其值设置为“ 5,7”。

PLEASE NOTE: I don't want to check for the property VALUE(me.name) but for the property NAME. 请注意:我不想检查属性VALUE(me.name),而是检查属性NAME。

Thank you. 谢谢。

You can use the in operator: 您可以使用in运算子:

if ("height" in me) {
  // object has a property named "height"
}
else {
  // no property named "height"
}

Note that if the object does not have a property named "height", you can still add such a property: 请注意,如果对象没有名为“ height”的属性,则仍可以添加这样的属性:

me.height = 100;

That works whether or not the object had a "height" property previously. 无论对象先前是否具有“ height”属性,该方法都有效。

There's also the .hasOwnProperty method inherited from the Object prototype: 还有从对象原型继承的.hasOwnProperty方法:

if (me.hasOwnProperty("height"))

The difference between that and a test with in is that .hasOwnProperty() only returns true if the property is present and is present as a direct property on the object, and not inherited via its prototype chain. 那和使用in进行的测试之间的区别是.hasOwnProperty()仅在存在该属性并且作为对象的直接属性存在并且不通过其原型链继承时才返回true。

您可以使用.hasOwnProperty

me.hasOwnProperty('height'); //false

Direct Answer: 直接回答:

if (Object.keys(me).indexOf("name") >= 0) {
    //do the stuff
}

BUT, what you should do, is create a contractual object/class/module, expecting me to have the height property. 但是,您应该做的是创建一个契约对象/类/模块,希望我拥有height属性。 If it doesn't, you should throw an exception. 如果不是,则应引发异常。 The worst things in programming are half ass expectations. 编程中最糟糕的事情是期望值的一半。 It not only breaks the SOLID precepts but also leads to scenarios like this, where the only solution are repetitive if/switch statements to make sure to treat all possibilities... 它不仅破坏了SOLID规范,而且导致了类似这样的情况,其中唯一的解决方案是重复性if / switch语句以确保处理所有可能性...

you can use 您可以使用

if (me.hasOwnProperty('height'))
{
 }
else
{
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM