let a = 5;
let b = 7;
方法一:加减法:
a = b - a;
b = b -a;
a = a + b;
或者:
a = a + b;
b = a - b;
a = a - b;
方法二: 乘除法:
a = a * b;
b = a / b;
a = a / b;
方法三:异或法
a = a ^ b;
b = a ^ b;
a = a ^ b;
方法四:ES6解构
let a = 1,
b = 2;
[a, b] = [b, a];
console.log(a + " " + b);
上面不理解的可以看下面的代码:
// let colors = ["red", "green", "blue"];
// // 将数组中的每一个值都重新赋值给一个新的变量用来保存
// let [firstColor, secondColor, last,aa] = colors;
// console.log(firstColor); // 'red'
// console.log(secondColor); // 'green'
// console.log(last); // 'blue'
// console.log(aa); // 'undefined'
方法五:利用数组的特性进行交换
var a = 1,
b = 2;
a = [a, b];
b = a[0];
a = a[1];
console.log(a + " " + b);
js实现交换两个变量的值(不使用临时变量)5种方式
最新推荐文章于 2023-10-17 15:28:08 发布