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('myOtherKey', $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:Checking to see if the object has the property itself or via its prototype: You use
propName in obj:Checking to see if the object has the property (directly, or via prototype) and it’s not undefined: You look for an undefined value:
Checking to see if the property is falsey (
undefined,null,0,"", or of course,false), regardless of why: Just use!:Regardless, usage: