JS 两个变量互换值

中间变量(临时变量)

var strA = "a"
var strB = "b"
var strC
strC = strB
strB = strA
strA = strC

若变量为数字,可使用加减法

//加法
var a = 2
var b = 3
a += b
b = a - b
a = a - b
//减法
a += b
b = a - b
a -= b

对象和数组

var a = "1" , b = "2"
对象的方法:
先把a变成一个对象,即
a={a:b,b:a}
b = a.a
a = a.b
数组的方法:
数组其实和对象的思想差不多
a = [a,b]
b = a[0]
a = b[1]

万能法(运用运算符优先级)

var a = "1", b= "code"
a = [b, b=a][0]
console.log(a,b)

ES6的解构赋值

什么是解构赋值?
解构赋值允许你使用类似数组或对象字面量的语法将数组和对象的属性赋给各种变量。这种赋值语法极度简洁,同时还比传统的属性访问方法更为清晰。

数组与迭代器的解构
语法:[ variable1, variable2, ..., variableN ] = array;
这将为variable1到variableN的变量赋予数组中相应元素项的值

可以去看看解构的赋值:http://es6.ruanyifeng.com/#docs/destructuring

let a = "one",b = "two";
[a, b] = [b, a];
console.log(a, b);//two one

利用try catch交换

var a=1,b=2;
a = (function () {;
    try{
        return b
    } finally {
        b = a
    }
})();
或字符串
var a = "aaa",
    b = "bbb";
a = (function () {;
    try {
        return b
    } finally {
        b = a
    }
})();
console.log(a, b);

异或运算(针对数字)

var a = 1; // 二进制:0001
var b = 2; // 二进制:0010
a = a ^ b; // 计算结果:a = 0011, b = 0010
b = a ^ b; // 计算结果:a = 0011, b = 0001
a = a ^ b; // 计算结果:a = 0010, b = 0001
自己可以动手试一下

例子:
var a = 0;
var b = 1;
a = (b = (a ^= b) ^ b) ^ a;
console.log(a,b)

例子:
var a = 0; // 二进制:0001
var b = 1; // 二进制:0010
a ^=b;
b ^=a;
a ^=b;
console.log(a,b)

数组的两个值的交换

var arr = [item0,item1,...,itemN];
//最初使用这段代码来交换第0个和第K(k<N)个元素
arr[0] = arr.splice(k, 1, arr[0])[0];

var arr = [1,2,3,"aaa","bbb","ccc"];
arr[0] = arr.splice(3, 1, arr[0])[0];
console.log(arr.toString())//aaa,2,3,1,bbb,ccc

via: http://www.jianshu.com/p/fb863e73862f

发表评论

Close Menu