Page 1 of 1

array_key_exists for javascript

Posted: Tue Nov 21, 2006 5:42 pm
by Luke
Is there a function/method similar to array_key_exists or isset (for arrays) for javascript? I can't find one... :(

Posted: Tue Nov 21, 2006 5:51 pm
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
}

Re: array_key_exists for javascript

Posted: Tue Nov 21, 2006 6:23 pm
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"

Posted: Tue Nov 21, 2006 6:24 pm
by Chris Corbyn
Doh! Sorry I thought you said array_keys(). My eyes are all fuzzy cos I'm tired :P

Posted: Tue Nov 21, 2006 6:32 pm
by Luke
no problem... that's useful anyway... thank you.