简体   繁体   中英

understanding how javascript's hasOwnProperty() method evaluates arguments

I'm new to javascript and need to check for a nested property. I was told that I can use .hasOwnProperty() method. How would I differentiate between the property being myVar variable's value , or the property name actually being myVar in the object? Do I need to extract the content's of myVar into a string before passing into the hasOwnProperty() ? So basically, does hasOwnProperty() always evaluate the argument to the string?

 if(main_hash.query.filtered.query.hasOwnProperty(myVar)){
      // do stuff
 }

Thank you in advance.

hasOwnProperty doesn't test values per say. It tests if a property exists on an object.

var test = {
    someproperty: ''
};

test.hasOwnProperty('someproperty');

This would return true because the property exists on the object. I believe it always expects a string value of the property name.

And equivalently doing this is the same:

var somevariable = 'someproperty';
test.hasOwnProperty(somevariable);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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