Reputation: 11886
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.
P.S. I'm using Google Chrome.
Upvotes: 1
Views: 374
Reputation: 4993
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]";
}
Upvotes: 2
Reputation: 95
They are two different objects. I use the second for JSON response, and the first for normal use in the code.
Upvotes: 0