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

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

    Because (1,2) == 2. You've stumbled across the comma operator (or simpler explanation here).

    Unless commas appear in a declaration list, parameter list, object or array literal, they act like any other binary operator. x, y evaluates x, then evaluates y and yields that as the result.

提交回复
热议问题