Jump to content
Sign in to follow this  
dgvirtual

Accessing Arrays with Named Indexes

Recommended Posts

I was fiddling with „Accessing Arrays with Named Indexes“ section examples of the Javascript tutorial and run into a situation I cannot explain. 

In short, I create an array 'person', then add elements to the array by index, and then add a third element by name. According to the tutorial, this should convert the array to an object (see here: https://www.w3schools.com/js/js_mistakes.asp) . Instead, after this I can access the variable 'person' as both an array (with two elements) and an object (or rather, a person.age property of the object). typeof 'person' reports: object.

var person = [];
person[0] = "John";
person[1] = "Doe";
person["age"] = 46;

Here is a link to the full test: https://www.w3schools.com/code/tryit.asp?filename=GHWE7BWHX1GH

Could someone explain what is happening here?

Share this post


Link to post
Share on other sites

3 things to answer your questions

Arrays strictly only have numerical indexes.

Adding a string index converts the array to a generic object.

You can access an object's properties through square bracket [] method, just like an array.

Share this post


Link to post
Share on other sites

OK, thank you, I see that adding this code:

const entries = Object.entries(person)

document.getElementById("demo3").innerHTML =
"entries: " + entries;

to my post results in printing all the object properties and values on the screen.

The only thing that I cannot understand is why the `person.length` reports 2 when the length of the object is actually 3 (2 does not change if I comment out the line that ads the third property and converts the array to an object).

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...