Javascript array in php style

advertisements

Possible Duplicate:
Associative arrays in Javascript?

Is it possible to do in javascript something like this:

array('one' => 'value-1','two'=> 'value-2');

And after that access it like this $var['one'] and to return value-1 I'm kinda new to JS, and google didn't gave me a good answer.


Yes and no - you can create an object like this:

var theObject = { one: "value 1", two: "value 2" };

but it's not an array. True arrays in JavaScript have strictly numeric indexes. (You can add string-named properties to a JavaScript array object, but they're not accounted for in the .length of the array.)

edit — to add properties to the object (or any object), you can use the . or [] operators:

theObject.newProperty = "something new";

theObject[ computeNewPropertyName() ] = "wow";

The second example shows the [] operator, which is used when the name of a property is computed dynamically some how (in the example, by a function call, but it could be any expression).