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.

Community
  • 1
  • 1
Uffo
  • 9,628
  • 24
  • 90
  • 154
  • the proper term for that type of array is an "associative array" which will provide much more information on Google. – Matt Whipple Jan 19 '13 at 21:15

4 Answers4

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

Dagg Nabbit
  • 75,346
  • 19
  • 113
  • 141
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 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 Jan 19 '13 at 21:24
  • @Uffo: You can use `theObject.five = '5'` or `theObject['five'] = '5'`. – Blender Jan 19 '13 at 21:27
  • @Uffo I'll update the answer. – Pointy Jan 19 '13 at 21:27
2

Yep, it's called an object:

var your_object = {
    'one': 'value-1',
    'two': 'value-2'
};
Blender
  • 289,723
  • 53
  • 439
  • 496
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"

AlexMost
  • 104
  • 7
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'
};
Beetroot-Beetroot
  • 18,022
  • 3
  • 37
  • 44