Created
April 15, 2013 15:07
-
-
Save glynthomas/5388787 to your computer and use it in GitHub Desktop.
JavaScript testing for empty array, object keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Javascript testing for empty (undefined) object or array | |
This is the problem, for JS object keys and for array's, not that I like really testing for undefined, I would rather set false or true and test for that, but ...; | |
var obj = { key: undefined }; | |
obj["key"] != undefined // false, but the key exists! | |
and also; | |
if (urlobject[3] == 'undefined') {} // again does not work as expected | |
solution for keys; | |
!("key" in obj) // true if "key" doesn't exist in object | |
!"key" in obj // ERROR! Equivalent to "false in obj" | |
Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty: | |
obj.hasOwnProperty("key") // true | |
solution for array; | |
if ((typeof urlobject[3]) === 'undefined') {} // works as expected | |
Original source: http://stackoverflow.com/questions/1098040/checking-if-an-associative-array-key-exists-in-javascript |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment