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

后端 未结 3 1077
难免孤独
难免孤独 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:38

    [1,2,3,4,5,6][1,2,3];
          ^         ^
          |         |
        array       + — array subscript access operation,
                        where index is `1,2,3`,
                        which is an expression that evaluates to `3`.
    

    The second [...] cannot be an array, so it’s an array subscript operation. And the contents of a subscript operation are not a delimited list of operands, but a single expression.

    Read more about the comma operator here.

提交回复
热议问题