js将x变量设置为y而不使用额外变量

时间:2017-09-09 07:39:41

标签: javascript

如果我有

Failed to add recipient: @localhost [SMTP: Invalid response code received from server (code: 501, response: 5.1.3 Invalid address [HKXPR02MB0695.apcprd02.prod.outlook.com])]

如何在没有中间附加变量的情况下设置这样的结果。

x = 5;
y = 6;

3 个答案:

答案 0 :(得分:2)

1)只能使用数学运算,你可以这样做。将总和保存到第一个变量中。然后在第二个中保持总和与当前值的差值,这将给出第一个值。在第一个变量之后,保持sum和seconds值的差值,这将给出第一个值。



let x = 5;
let y = 6;

console.log(`x is ${x}, y is ${y}`);

x = x + y;
y = x - y;
x = x - y;

console.log(`x is ${x}, y is ${y}`);




2)使用语言功能,您可以通过 Array Destructuring 来完成。



let x = 5;
let y = 6;

console.log(`x is ${x}, y is ${y}`);

[x, y] = [y, x];

console.log(`x is ${x}, y is ${y}`);




3)如果数字是整数,请使用着名的XOR swap algorithm



let x = 5;
let y = 6;

console.log(`x is ${x}, y is ${y}`);

x = x ^ y;
y = x ^ y;
x = x ^ y;

console.log(`x is ${x}, y is ${y}`);




答案 1 :(得分:0)

使用es2015,你可以

[x,y] = [y,x]

答案 2 :(得分:0)

1)您可以使用第三个变量来交换x和y值。所以,如果第三个变量是temp。

第一步 temp = x

第二步 x = y

第3步 y = temp

 var x = 5;
 var y = 6;
 var temp = 0;

  temp = x;
  x = y;
  y = temp;

  console.log('x =',x);
  console.log('y =',y);

2) ES6

var x = 5,
    y = 6;

[x, y] = [y, x];

console.log('x =', x, 'y =', y);