Hello Guest
* *
Welcome, Guest. Please login or register.
2017-10-21, 23:27

Login with username, password and session length

Author Topic: Checking if an associative array key exists  (Read 8459 times)

0 Members and 1 Guest are viewing this topic.

Offline Marook

  • Administrator
  • Newbie
  • *****
  • Posts: 25
    • View Profile
Checking if an associative array key exists
« on: 2013-04-02, 11:03 »
Actually, checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined?

Code: [Select]
var obj = { key: undefined };
obj["key"] != undefined // false, but the key exists!

You should instead use the in operator:

Code: [Select]
"key" in obj // true, regardless of the actual value
If you want to check if a key doesn't exist, remember to use parenthesis:

Code: [Select]
!("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:

Code: [Select]
obj.hasOwnProperty("key") // true
Code: [Select]
var aa = {hello: "world"};
alert( aa["hello"] );      // popup box with "world"
alert( aa["goodbye"] );    // popup boc with "undefined"

// note the three equal signs so that null won't be equal to undefined
if( aa["goodbye"] === undefined ) {
    // do something
}

// this works even if you have {"goodbye": undefined}
if( "goodbye" in aa ) {
    // do something
}

Tags: object array key exists 
 

Recent

Members
  • Total Members: 1
  • Latest: Marook
Stats
  • Total Posts: 34
  • Total Topics: 34
  • Online Today: 3
  • Online Ever: 82
  • (2013-05-08, 10:46)
Users Online
Users: 0
Guests: 1
Total: 1