1、交换变量
通常交换两个变量的方法都需要一个额外的临时变量,如下:
let a = 1;
let b = 2;
let temp;
temp = a;
a = b;
b = temp;
console.log(a); //2
console.log(b); //1
temp是一个临时变量,它先保存a的值。然后把b值赋给a,然后将temp值赋给b。
如果使用解构的方式,就不需要temp变量。
let a = 1;
let b = 2;
[a,b] = [b,a];
console.log(a); //2
console.log(b); //1
[a,b] = [b,a]是解构赋值,右边,创建了一个数组[b,a],即[2,1]。这个数组2被赋值了给a,1被赋值给b。
虽然这种方式也创建了临时数组,但这种方式给看起来至少更简洁,使用解构还可以交换两个以上的变量。
let a = 1;
let b = 2;
let c = 3;
let d = 4;
[a,b,c,d] = [d,c,b,a];
console.log(a);
console.log(b);
console.log(c);
console.log(d);
2、访问数组中元素
有种场景,我们可能希望有一个空数组。并且希望访问数组的第一个、第二个或第n个项,但是如果该项不存在,则使用指定默认值。
通常会使用数组的length属性来判断。
const colors = [];
let firstColor = 'white';
if(colors.length > 0) {
firstColor = colors[0];
}
console.log(firstColor);
使用解构:
const colors = [];
const [firstColor = 'white'] = colors;
console.log(firstColor); //white
const [firstColor = 'white'] = colors解构将colors数组的第一个元素赋值给firstColor变量。如果数组在索引0处没有任何元素,则分配”white“默认值。
当然,如果我们只想访问第二个元素:
const colors = [];
const [, secondColor = 'black'] = colors;
console.log(secondColor);
需要注意的是:解构左侧的逗号:它表示忽略第一个元素,secondColor使用colors数组中索引为1的元素进行赋值。