I recently came across some code which I am a little confused about. Below is similar code, have a look:
var x = [];
console.log(x); // prints [] (no surprise)
x[0] = "abc";
console.log(x); // prints ["abc"] (no surprise)
x["test"] = "testing"
console.log(x); // prints ["abc"]
console.log(x.test); // prints "testing"
so in this case.. the same variable, x
, is both array and an object. How is this possible? If it acts as both, then console.log(x)
should print something like ["abc",test:"testing"]
but that syntax is wrong.
So whats happening in this case?
All Arrays are Objects, (not only them, everything in JavaScript is an Object (except the primitives though))
console.log([] instanceof Object);
// true
just that they are special kind of objects which process integer keys differently.
So, you can expect them to act like normal JavaScript Objects. You can add arbitrary properties to them.
About the console.log
result,
[ 'abc', test: 'testing' ]
is just a representation given by the implementation. If the representation has a key : value
format, then it is a normal property associated with that array. That's all.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments