Reputation: 2046
I understand that when index names are used to push values in Javascript, they essentially work like objects. But what I don't understand is the following behaviour -
person = [];
person[0] = "Someone";
person["test"] = "SomeoneElse"
Inputting person
on the console prints ["Someone"]
and I could see no information about person.test
.
person.test
does print SomeoneElse
. However, if I go console.log(person)
, I get ["Someone", test: "SomeoneElse"]
.
Curious to check if this makes sense, I tried to create a structure like this one -
var experiment = ["Someone1", test1: "SomeoneElse1"]
and what I get is
Uncaught SyntaxError: Unexpected token
What am I missing?
Thanks in advance!
Upvotes: 3
Views: 3734
Reputation: 87
typing person in console is like having an alert(person);
or passing its value to a variable or element, so it is more like you want to get the first set of readable values. That is the reason why it is showing you the values inside, you can try adding person[1] = *something;*
, then it will display someone, something
console.log(person) - it displays all the items inside an object. It is more like informing you of what is inside, like a text visualizer in your IDE
var experiment = ["Someone1", test1: "SomeoneElse1"]
- it will absolutely throw an exception there is no such format like this on initializing values, at least it is expecting an array format like var experiment = ["Someone1", "SomeoneElse1"]
Upvotes: 0
Reputation: 522322
Typing
person
on the console prints["Someone"]
.
Array.prototype.toString
formats this output, and it only considers the "array values" of itself without other properties.
However, if I go
console.log(person)
, I get["Someone", test: "SomeoneElse"]
.
console.log
outputs other information about the object, including own properties.
Uncaught SyntaxError: Unexpected token
Because that is bogus syntax; the array literal syntax doesn't allow keys, because array values aren't supposed to have keys. Arrays are a numerically indexed list of values. Merely by the fact that under the hood those lists are implemented using objects (because everything in Javascript is an object of some kind or another) are you able to set "non numeric keys" on the array. That doesn't mean you're using the array correctly though.
Also see Are JavaScript Array elements nothing more than Array object properties?
Upvotes: 5
Reputation: 64526
This is because an array in JavaScript is also an object itself, and objects can have properties. So it is perfectly valid to have an array with elements, but also have properties set on the array object.
The second example doesn't work because the [...,...,...]
syntax is specifically for instantiating an array and its elements.
Upvotes: 1