array_key_exists for javascript

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

array_key_exists for javascript

Post by Luke »

Is there a function/method similar to array_key_exists or isset (for arrays) for javascript? I can't find one... :(
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

It seems like I always find a solution like 3 seconds after posting a question...

Code: Select all

if(document.forms['review'] != undefined){
    // Do stuff
}
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: array_key_exists for javascript

Post by Chris Corbyn »

The Ninja Space Goat wrote:Is there a function/method similar to array_key_exists or isset (for arrays) for javascript? I can't find one... :(
No but this does the trick:

Code: Select all

Array.prototype.getKeys = function()
{
    var ret = new Array();
    for (var key in this) ret.psuh(key);
    return ret;
}
To use it just do:

Code: Select all

var myArray = new Array();
myArray["x"] = 42;
myArray["y"] = 10;

var mykeys = myArray.getKeys();

alert(myKeys[0]); // "x"
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Doh! Sorry I thought you said array_keys(). My eyes are all fuzzy cos I'm tired :P
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

no problem... that's useful anyway... thank you.
Post Reply