Is JavaScript array index a string or an integer?

前端 未结 5 786
野趣味
野趣味 2020-11-27 20:03

I had a generic question about JavaScript arrays. Are array indices in JavaScript internally handled as strings? I read somewhere that because arrays are objects in JavaScri

5条回答
  •  北海茫月
    2020-11-27 20:54

    Formally, all property names are strings. That means that array-like numeric property names really aren't any different from any other property names.

    If you check step 6 in the relevant part of the spec, you'll see that property accessor expressions are always coerced to strings before looking up the property. That process is followed (formally) regardless of whether the object is an array instance or another sort of object. (Again, it just has to seem like that's what's happening.)

    Now, internally, the JavaScript runtime is free to implement array functionality any way it wants.

    edit — I had the idea of playing with Number.toString to demonstrate that a number-to-string conversion happens, but it turns out that the spec explicitly describes that specific type conversion as taking place via an internal process, and not by an implicit cast followed by a call to .toString() (which probably is a good thing for performance reasons).

提交回复
热议问题