Is JavaScript array index a string or an integer?

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

    Let's see:

    [1]["0"] === 1 // true
    

    Oh, but that's not conclusive, since the runtime could be coercing "0" to +"0" and +"0" === 0.

    [1][false] === undefined // true
    

    Now, +false === 0, so no, the runtime isn't coercing the value to a number.

    var arr = [];
    arr.false = "foobar";
    arr[false] === "foobar" // true
    

    So actually, the runtime is coercing the value to a string. So yep, it's a hash table lookup (externally).

提交回复
热议问题