示例 1:使用临时变量
//JavaScript program to swap two variables
//take input from the users
let a = prompt('Enter the first variable: ');
let b = prompt('Enter the second variable: ');
//create a temporary variable
let temp;
//swap variables
temp = a;
a = b;
b = temp;
console.log(`The value of a after swapping: ${a}`);
console.log(`The value of b after swapping: ${b}`);
输出
Enter the first variable: 4 Enter the second variable: 2 The value of a after swapping: 2 The value of b after swapping: 4
这里,
- 我们创建了一个temp变量来临时存储a的值。
- 我们将b的值赋给了a。
- temp的值被赋给了b
结果,变量的值被交换了。
注意:您也可以使用此方法交换字符串或其他数据类型。
示例 2:使用ES6(ES2015)解构赋值
//JavaScript program to swap two variables
//take input from the users
let a = prompt('Enter the first variable: ');
let b = prompt('Enter the second variable: ');
//using destructuring assignment
[a, b] = [b, a];
console.log(`The value of a after swapping: ${a}`);
console.log(`The value of b after swapping: ${b}`);
输出
Enter the first variable: 4 Enter the second variable: 2 The value of a after swapping: 2 The value of b after swapping: 4
这里,使用了一个名为解构赋值的新ES6特性[a, b] = [b, a]
来交换两个变量的值。如果[a, b] = [1, 2, 3]
,则a的值为1,b的值为2。
- 首先创建一个临时数组[b, a]。这里[b, a]的值将是
[2, 4]
。 - 进行数组解构,即
[a, b] = [2, 4]
。
结果,变量的值被交换了。
您可以在JavaScript解构赋值中了解更多关于解构的知识。
您也可以使用算术运算符交换变量的值。
示例 3:使用算术运算符
//JavaScript program to swap two variables
//take input from the users
let a = parseInt(prompt('Enter the first variable: '));
let b = parseInt(prompt('Enter the second variable: '));
// addition and subtraction operator
a = a + b;
b = a - b;
a = a - b;
console.log(`The value of a after swapping: ${a}`);
console.log(`The value of b after swapping: ${b}`);
输出
Enter the first variable: 4 Enter the second variable: 2 The value of a after swapping: 2 The value of b after swapping: 4
此方法仅使用两个变量,并使用算术运算符+
和-
交换变量的值。
这里使用了parseInt(),因为prompt()
从用户那里获取输入作为字符串。当数字字符串相加时,它表现得像字符串。例如,'2' + '3' = '23'
。所以parseInt()
将数字字符串转换为数字。
要了解更多关于类型转换的信息,请访问JavaScript类型转换。
让我们看看上面的程序是如何交换值的。最初,a是4,b是2。
a = a + b
将值4 + 2
赋给a(现在是6)。b = a - b
将值6 - 2
赋给b(现在是4)。a = a - b
将值6 - 4
赋给a(现在是2)。
最后,a是2,b是4。
注意:如果两个变量都是数字类型,您可以使用算术运算符(+
, -
)。
示例 4:使用按位异或运算符
//JavaScript program to swap two variables
//take input from the users
let a = prompt('Enter the first variable: ');
let b = prompt('Enter the second variable: ');
// XOR operator
a = a ^ b
b = a ^ b
a = a ^ b
console.log(`The value of a after swapping: ${a}`);
console.log(`The value of b after swapping: ${b}`);
输出
Enter the first variable: 4 Enter the second variable: 2 The value of a after swapping: 2 The value of b after swapping: 4
如果两个操作数不同,按位异或运算符求值为true
。要了解更多关于按位运算符的信息,请访问JavaScript按位运算符。
让我们看看上面的程序是如何交换值的。最初,a是4,b是2。
a = a ^ b
将值4 ^ 2
赋给a(现在是6)。b = a ^ b
将值6 ^ 2
赋给b(现在是4)。a = a ^ b
将值6 ^ 4
赋给a(现在是2)。
最后,a是2,b是4。
注意:您只能对整数(整数)值使用此方法。