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

前端 未结 3 915
半阙折子戏
半阙折子戏 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: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.

提交回复
热议问题