3

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.

1
  • the proper term for that type of array is an "associative array" which will provide much more information on Google. Commented Jan 19, 2013 at 21:15

4 Answers 4

3

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).

Sign up to request clarification or add additional context in comments.

3 Comments

and if I want later to add new items to the object, how do I do it? let's say that I have one,two in the object already, and I want to add five,six to the object, but in other part of the code, how do I do it?
@Uffo: You can use theObject.five = '5' or theObject['five'] = '5'.
@Uffo I'll update the answer.
2

Yep, it's called an object:

var your_object = {
    'one': 'value-1',
    'two': 'value-2'
};

Comments

2

hah))) in normal languages this is called a dictionary))) In javascript you can create dictionary or object like this

    a = {"one":"value-1", "two":"value-2"}

a["one"] returns "value-1"

Comments

1

Try

Array (an ordered, indexed set of items) :

var myArray = [
    'value-1',
    'value-2'
];

Object (an orderless set of keyed properties):

var myObject = {
    'one': 'value-1',
    'two': 'value-2'
};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.