Is JavaScript array index a string or an integer?

前端 未结 5 820
野趣味
野趣味 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:55

    In JavaScript there are two type of arrays: standard arrays and associative arrays (or an object with properies)

    • [ ] - standard array - 0 based integer indexes only
    • { } - associative array - JavaScript objects where keys can be any strings

    So ...

    var arr = [ 0, 1, 2, 3 ];
    

    ... is defined as a standard array where indexes can only be integers. When you do arr["something"] since something (which is what you use as index) is not an integer you are basically defining a property to the arr object (everything is object in JavaScript). But you are not adding an element to the standard array.

提交回复
热议问题