Are Javascript arrays sparse?

后端 未结 7 2129
情书的邮戳
情书的邮戳 2020-11-22 08:12

That is, if I use the current time as an index into the array:

array[Date.getTime()] = value;

will the interpreter instantiate all the elem

7条回答
  •  有刺的猬
    2020-11-22 08:43

    Yes, they are. They are actually hash tables internally, so you can use not only large integers but also strings, floats, or other objects. All keys get converted to strings via toString() before being added to the hash. You can confirm this with some test code:

    
    

    Displays:

    array[0] = zero, typeof(0) == string
    array[1254503972355] = now, typeof(1254503972355) == string
    array[3.14] = pi, typeof(3.14) == string
    

    Notice how I used for...in syntax, which only gives you the indices that are actually defined. If you use the more common for (var i = 0; i < array.length; ++i) style of iteration then you will obviously have problems with non-standard array indices.

提交回复
热议问题