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 Answer 1

2

In javascript you can achieve this with objects:

var arr = {
    foo: 'bar',
    12: true
};
Sign up to request clarification or add additional context in comments.

4 Comments

How do you then loop through an object's properties?
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.
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: 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.