views:

41

answers:

1

Is it possible to create a javascript array similar to PHP's method which allows you to define the keys during creation?

$arr = array("foo" => "bar", 12 => true);

Or can this only be done like:

myArray["foo"] = "bar";
myArray[12] = true;
+1  A: 

In javascript you can achieve this with objects:

var arr = {
    foo: 'bar',
    12: true
};
Paolo Bergantino
How do you then loop through an object's properties?
Brett
Of course. I've done this before.for (var property in object) { alert(object[property]);}So I take it then that it isn't possible to declare arrays in this way? Thanks.
Brett
Arrays? What do you mean?
Paolo Bergantino
What I mean is your solution does not create an array, but an object. So I can't call arr[0] and get 'bar' returned. Also, I won't be able to do something like (again, using PHP as an example) $arr = array(1 => "bar", true), where the second value will automatically have an incremented key value ($arr[2] => true).
Brett
@Brett: With the declaration in my answer you can call arr['foo'] to get 'bar', but in PHP you wouldn't be able to do $arr[0] to get 'bar' if you declared it as "foo" => "bar", same with JS. Objects in Javascript let you emulate the associative array features of PHP but as far as the second example goes that's just not a language feature.
Paolo Bergantino
Thanks for clearing that up.
Brett