Suppose I have a javascript object like this:
window.config
config.UI = {
"opacity": {
"_type": "float",
"_tag": "input",
"_value": "1",
"_aka": "opacity",
"_isShow":"1"
}
How can I judge if the “opacity” object has a property named “_test”?
like
var c=config.ui.opacity;
for(var i in c)
{
//c[i]=="_test"?
}
How do I find out if it’s assigned as well?
There are at least three ways to do this; which one you use is largely up to you and sometimes even a matter of style, though there are some substantive differences:
if..inYou can use
if..in:…because when used in a test (as opposed to the special
for..inloop),intests to see if the object or its prototype (or its prototype’s prototype, etc.) has a property by that name.hasOwnPropertyIf you want to exclude properties from prototypes (it doesn’t much matter in your example), you can use
hasOwnProperty, which is a function all objects inherit fromObject.prototype:Just retrieve it and check the result
Finally, you can just retrieve the property (even if it doesn’t exist) and the decide what to do with the result by looking at the result; if you ask an object for the value of a property it doesn’t have, you’ll get back
undefined:or
Being defensive
If it’s possible that
config.UIwon’t have anopacityproperty at all, you can make all of those more defensive:That last one works because the
&&operator is particularly powerful in JavaScript compared with some other languages; it’s the corollary of the curiously-powerful||operator.