代码如下:
let a = 1, b = 10
a = a + b - (b = a)
console.log('first: ', a, b)
a = a ^ b
b = a ^ b
a = b ^ a
console.log('second: ', a, b)
a = {a, b}
b = a.a
a = a.b
console.log('third: ', a, b)
a = [a, b]
b = a[0]
a = a[1]
console.log('fourth: ', a, b)
a = a + b
b = a - b
a = a - b
console.log('fifth: ', a, b)
a = a * b
b = a / b
a = a / b
console.log('sixth: ', a, b)
//注意这里前面要有;或者上面的console.log后面要有;否则报错
;[a, b] = [b, a]
console.log('seventh: ', a, b)
除了第一种是运算顺序、最后一种是解构赋值,其它的方法主要的思路都是:先产生一个与这两个变量有关的一个新的值,然后重新计算。
运行结果截图如下:
注意:js中不加分号主要在圆括号(,方括号[,正则开头的斜杠,加号,减号(后三种比较少见,前面两种主要体现在IIFE立即执行的函数表达式,数组)5种情况下容易出问题。
参考链接:https://blog.csdn.net/q1056843325/article/details/53223914?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-2.baidujs&dist_request_id=1328679.11011.16161628507793059&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-2.baidujs