简体   繁体   中英

How and why does assigning values with string keys work in JS arrays?

See this code:

 var arr = []; arr.foo = 'bar'; console.log(arr.foo); 

Now, we see that arr.foo doesnt throw an error and works, but technically it should throw an error so why doesn't it?

Also, how is the above represented in memory, considering array blocks are mostly allocated memory in continuous location with the index of the offset, how does that work here?

...technically it should throw an error...

No, it works entirely as described in the specification .

It works because standard JavaScript arrays aren't really arrays ,* they're just objects backed by Array.prototype with a special length property and special handling for property names that are array indexes according to the specification. A property with any other name is just a normal object property, not an array entry.

Since arrays are objects, they can have non-array-entry properties, just like any other object.

FWIW, the definition of an array index is:

An integer index is a String-valued property key that is a canonical numeric String (see 7.1.16) and whose numeric value is either +0 or a positive integer ≤ 2 53 -1. An array index is an integer index whose numeric value i is in the range +0 ≤ i < 2 32 -1.

Note that typed arrays are true arrays; but they're also objects, and you can add non-array-entry properties to them, too.


* (that's a post on my anemic little blog)

Arrays are Objects and you can put inside different kinds of objects like strings, like dictionaries, another objects in general etc. when you write:

arr.foo="bar"

you are puting a value "bar" for the name access foo. your variable arr is now

 arr={foo:"bar"}

and you can access it like you did arr.foo if you want more information check te page from the w3c here https://www.w3schools.com/js/js_arrays.asp in the section array object.

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