简体   繁体   中英

Javascript associative arrays differ on variable declaration

I notice a difference when I declare a variable as an array or object and then add elements to it.

When I declare my variable as below:

var my_array = [];
my_array["a"] = 'first';
my_array["b"] = 'second';
console.log(my_array);

I get the following result:

[a: "first", b: "second"] 

However, when I do the following:

var my_array = {};
my_array["a"] = 'first';
my_array["b"] = 'second';
console.log(my_array);

This is the result I get:

Object {a: "first", b: "second"} 

What is really going on here?! Is one way standard, and the other not?! What are the downsides with compatibility?!

Thanks in advance.

PS I'm using Google Chrome.

The first is an array and the secound is an object, which one to use depands on your goal, if you need arrays the array will be more usefull and effiecent than using an "array" object.

Further more an object can be used like this: myObject.a

While an array can be only used like this: myArray["a"]

Another diffrence is in the toString method. For an array it returns Banana,Orange,Apple,Mango (for example) and for an object it returns [object Object] (for example).

For further reading: What is the difference between an array and an object?

Check if is array:

function isArray(obj) {
    return Object.prototype.toString.call(obj) === "[object Array]";
}

They are two different objects. I use the second for JSON response, and the first for normal use in the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM