Why does [5,6,8,7][1,2] = 8 in JavaScript?

后端 未结 3 1032
难免孤独
难免孤独 2020-11-22 13:04

I can\'t wrap my mind around this quirk.

[1,2,3,4,5,6][1,2,3]; // 4
[1,2,3,4,5,6][1,2]; // 3

I know [1,2,3] + [1,2] = \"1,2,31,2\"

3条回答
  •  渐次进展
    2020-11-22 13:30

    [1,2,3,4,5,6][1,2,3];
    

    Here the second box i.e. [1,2,3] becomes [3] i.e. the last item so the result will be 4 for example if you keep [1,2,3,4,5,6] in an array

    var arr=[1,2,3,4,5,6];
    
    arr[3]; // as [1,2,3] in the place of index is equal to [3]
    

    similarly

    *var arr2=[1,2,3,4,5,6];
    
     // arr[1,2] or arr[2] will give 3*
    

    But when you place a + operator in between then the second square bracket is not for mentioning index. It is rather another array That's why you get

    [1,2,3] + [1,2] = 1,2,31,2
    

    i.e.

    var arr_1=[1,2,3];
    
    var arr_2=[1,2];
    
    arr_1 + arr_2; // i.e.  1,2,31,2
    

    Basically in the first case it is used as index of array and in the second case it is itself an array.

提交回复
热议问题