I need to learn how to pass an associative array to a function so that I could do the following within the function:
function someName($argums) {
if (gettype($argums) != 'array' ||
!array_key_exists('myOneKey', $argums) ||
!array_key_exists('myOther开发者_开发技巧Key', $argums)) {
return false;
}
/*do other stuff*/
}
(That's how I would do it in PHP that I am looking for in JavaScript.)
All Javascript objects are associative arrays, so this is really easy. You actually have a few options, because an object can have properties of its own, properties it inherits from its prototype object, properties with undefined values, and properties with "falsey" values (undefined
, null
, 0
, ""
, or of course, false
). (There's a difference between an object not having a property and having one with an undefined value.)
Checking to see if the object has the properties itself: You use obj.hasOwnProperty
:
function someName(obj) {
if (!obj ||
!obj.hasOwnProperty('myOneKey') ||
!obj.hasOwnProperty('myOtherKey'))
return false;
}
// Do other stuff
}
Checking to see if the object has the property itself or via its prototype: You use propName in obj
:
function someName(obj) {
if (!obj ||
!('myOneKey' in obj) ||
!('myOtherKey' in obj))
return false;
}
// Do other stuff
}
Checking to see if the object has the property (directly, or via prototype) and it's not undefined: You look for an undefined value:
function someName(obj) {
if (!obj ||
typeof obj.myOneKey === "undefined" ||
typeof obj.myOtherKey === "undefined")
return false;
}
// Do other stuff
}
Checking to see if the property is falsey (undefined
, null
, 0
, ""
, or of course, false
), regardless of why: Just use !
:
function someName(obj) {
if (!obj ||
!obj.myOneKey ||
!obj.myOtherKey)
return false;
}
// Do other stuff
}
Regardless, usage:
var obj = {
myOneKey: 'fred',
myOtherKey: 'barney'
};
someName(obj);
精彩评论