How does [b][b = a,0] swap between a and b?

前端 未结 2 470
栀梦
栀梦 2020-12-18 04:06

As gdoron pointed out,

var a = \"a\";
var b = \"b\";

a = [b][b = a,0];

Will swap a and b, and although it looks

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-18 04:35

    var a = "a";
    var b = "b";
    
    a = [b][b = a, 0];
    

    Let's break the last line into pieces:

    [b]       // Puts b in an array - a safe place for the swap.
    [b = a]   // Assign a in b
    [b = a,0] // Assign a in b and return the later expression - 0 with the comma operator.
    

    so finally it is a =[b][0] - the first object in the [b] array => b assigned to a

    Live DEMO

    read @am not I am comments in this question:
    When is the comma operator useful?
    It's his code...

提交回复
热议问题