Javascript array php style

Possible duplicate:
Associative arrays in Javascript?

Is it possible in javascript to do something like this:

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

      

And after that, get access to this as $var['one']

well as return value-1

. I'm new to JS and google didn't give me a good answer.

+3


source to share


4 answers


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

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

      

but it is not an array. True arrays in JavaScript have strictly numeric indices. (You can add string name properties to a JavaScript array object, but they are not counted in the .length

array.)



edit - to add properties to an object (or any object) you can use the operators .

or []

:

theObject.newProperty = "something new";

theObject[ computeNewPropertyName() ] = "wow";

      

The second example shows an operator []

that is used when the property name is dynamically evaluated in some way (in the example, by calling a function, but it can be any expression).

+3


source


Yes, it is called an object:



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

      

+2


source


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

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

      

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

+2


source


Try

Array (ordered, indexed set of elements):

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

      

Object (a jumbled collection of key properties):

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

      

+1


source







All Articles