简体   繁体   中英

Name Indexes in Javascript - Array / Object?

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!

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?

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.

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"]

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