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;
asked Sep 20, 2010 at 5:26
Brett
2,7567 gold badges33 silver badges51 bronze badges
1 Answer 1
In javascript you can achieve this with objects:
var arr = {
foo: 'bar',
12: true
};
answered Sep 20, 2010 at 5:27
Paolo Bergantino
490k83 gold badges524 silver badges437 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Brett
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
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).
Paolo Bergantino
@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.
lang-js