开发者

JavaScript - short way of declaring an associative array

Is there a short way of declaring an associative array li开发者_如何转开发ke in PHP?

$myArray = array('a' => 'b'); // PHP Way

In JavaScript I'd do it this way:

var myArray = [];
myArray['a'] = 'b';

I'm not looking for JavaScript objects.


Declare an object like this:

var myArray = {"a": "b", "c": "d"};

... and then refer to each item like this:

var somethingElse = myArray["a"]; //Sets "somethingElse" to "b".

As @Chris and @Marc mention in the comments: in JavaScript, objects ARE associative arrays, and vice versa, they just refer to two different ways of doing the same thing. For Example...

var somethingElse = myArray["a"];
var anotherVariable = myArray.a;

... do the same thing.


JavaScript does not have associative arrays. In your example, you declare myArray as array but then you assign an object to it. So your code is not different from this:

var myObject = {};
myObject['a'] = 'b';

Update: A little correction. Actually, the original code does not destroy the array. It just appends a regular property to it. That's possible because JavaScript arrays are a subset of JavaScript objects.


I'm not looking for JavaScript objects.

There are no "associative arrays" in JavaScript, just objects comprised of property names and values which can be treated as such. So, what you are looking for is in fact objects. In fact, this example from your question is working with an object:

var myArray = [];
myArray['a'] = 'b';
alert(typeof myArray); // 'object'

You initially construct the object using the array literal syntax:

var myArray = [];

which means you have created an object which inherits from Array.prototype. So essentially, you are dealing with an object which has been augmented with the methods stored in Array.prototype.

To check that myArray is actually an array (well, I would say JavaScript arrays are pseudo-arrays), you can check its constructor:

alert(typeof myArray === 'object' && myArray.constructor === Array);

There's a better way which will also identify arrays constructed in different windows and frames:

alert(Object.prototype.toString.apply(myArray) === '[object Array]');

You can also use instanceOf:

alert(myArray instanceof Array);

or Array.isArray:

alert(Array.isArray(myArray));


In javascript, associative arrays, keyed collections, hashes, ... whatever you want to call them, are not a special type. All the following are good.

a = {}
a[3] = 15
a.b = "c"
a['def'] = 'something'

This code produces a single valid object with the properties you would expect. All of them. You can combine a conventionally indexed array and an associative array in one object.

As to declaring a whole bunch at once, the usual syntax is:

a = {
    'key1' : 'val1',
    'key2' : val2,
    key3 : val3,
    key4 : "val4"
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜