JS Array a['1'] doesnot gives an error

前端 未结 3 906
半阙折子戏
半阙折子戏 2021-01-28 06:05

I have declared an array a = [1,2,3,4,5]

When I write a[1] it returns 2 which is perfectly fine but when I write a[\'1\']

相关标签:
3条回答
  • 2021-01-28 06:07

    First of all, array is also object having property names as 0,1,2,....n

    Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method. [Ref]

    0 讨论(0)
  • 2021-01-28 06:08

    In JS an Array is basically an Object and thus mostly behaves like one. In this case, these are equivalent as long as you dont access Array's .length or try iterating a:

    const a = {"0": foo};    
    const b = ["foo"];
    

    Also this would work:

    const a = ["foo"];
    a.bar = "baz";
    
    console.log(a);
    

    So that a[1] and a['1'] are equivalent is exactly what's to be expected.

    0 讨论(0)
  • 2021-01-28 06:13

    All property names are strings.

    If you pass a number, it gets converted to a string before being used to look up the property value.

    console.log(1 == '1');

    0 讨论(0)
提交回复
热议问题