JS 不声明第三个变量的情况下实现两数变换

1.

1     var a = 1;
2     var b = 2;
3     a = a + b; //3
4     b = a - b; //1
5     a = a - b; //2
6     console.log(a);
7     //2
8     console.log(b);
9     //1

2.

    var a = 1;
    var b = 2;
    a ^= b;
    b ^= a;
    a ^= b;
    console.log(a);
    //2
    console.log(b);
    //1

console.log((a ^= b) === (a ^ b) + b)
//true

3.

 1     var a = 1;
 2     var b = 2;
 3     a = [a, b];
 4     b = a[0];
 5     a = a[1];
 6 
 7     console.log(a);
 8     //2
 9     console.log(b);
10     //1

4.

1     var a = 1;
2     var b = 2;
3     a = [b, b = a][0];
4     console.log(a);
5     //2
6     console.log(b);
7     //1

5.

    var a = 1;
    var b = 2;
    a = { a: b, b: a };
    b = a.b;
    a = a.a
    console.log(a);
    //2
    console.log(b);
    //1

6.

1     var a = 1;
2     var b = 2;
3     [a, b] = [b, a]
4     console.log(a);
5     //2
6     console.log(b);
7     //1

 

posted @ 2019-12-21 17:21  半糖也甜吖  阅读(405)  评论(0编辑  收藏  举报