2021年4月11日星期日

Why does array allow string as an index in JavaScript

As we already know the main difference between array and object is:

If you want to supply specific keys, the only choice is an object. If you don't care about the keys, an array it is.

(Read more here: Array vs. Object efficiency in JavaScript)

Besides, according to MDN's docs says that

Arrays cannot use strings as element indexes (as in an associative array) but must use integers

However, I was so surprised this

var array = ["hello"];  array["hi"] = "weird";  > ["hello", hi: "weird"]  

The content structure of the array looks so weird. Even more, when I check the type of array it returns

Array.isArray(array) // true  
https://stackoverflow.com/questions/67030137/why-does-array-allow-string-as-an-index-in-javascript April 10, 2021 at 09:57AM

没有评论:

发表评论