普通的解构赋值就不详细说了,说一说特殊情况
1、不完全解构(等号两边模式相同,但是变量数量不同或解构的值的数量不同)
a、需要被赋值变量的数量 > 解构的值的数量
let [a] = [];
console.log(a); //undefined
let [a,b] = [1];
console.log(a); //1
console.log(b);//undefined
相当于找不到座位的小朋友就得undefined。
b、需要赋值的变量的数量 < 解构的值的数量
let [a,b] = [1,2,3];
console.log(a); //1
console.log(b); //2
把解构的值按前后顺序对号入座,多出来的蒸发掉。
2、带默认值
var [x = 'a'] = [];
console.log(x); // x='a'
let [x, y = 'b'] = ['a',];
console.log(x); // x='a'
console.log(y); // y='b'
let [x, y = 'b'] = ['a', undefined];
console.log(x); // x='a', y='b'
console.log(y); // y='b'
let [x, y = 'b'] = ['a', null];
console.log(x); // x='a', y='null'
console.log(y); // y='null'
如果解构的值是空或者undefined,那么会使用默认值;
如果是null,则会使用null;
如果有实际值,则会覆盖默认值。
3、对象的解构赋值
let { username: username, password : password} = { username: "aaa", password: "bbb" };
console.log(username); //aaa
console.log(password); //bbb
let { username, password} = { username: "aaa", password: "bbb" };
console.log(username); //aaa
console.log(password); //bbb
let { username , password} = { password: "aaa", username: "bbb" };
console.log(username); //bbb
console.log(password); //aaa
数组的解构赋值是根据元素的次序排列的;而对象的解构赋值,会去找同名属性对号入座!
let { user, pass } = { username: "aaa", password: "bbb" };
console.log(user); //undefined
console.log(pass); //undefined
解构的对象中没找到同名属性,undefined。
4、字符串的解构赋值
const [a,b,c,d,e] = "我是你爸爸";
console.log(c); //你
// 数组、类似数组的对象都有一个length属性(名字自定义)
let {length : len} = [1,2,3,4,5,22];
console.log(len); //6
数组、类似数组的对象都有一个length属性(名字自定义)。
let {length : len02} = 'hello';
console.log(len02); //5
5、解构赋值干啥用?
a、交换变量
let [x, y] = [111,222];
[x, y] = [y, x];
console.log([x, y]); // [222, 111]
b、获取函数的多个返回值
function bb(){
return [1, 2, 3];
}
let x = bb();
console.log(x[1]); //2
//返回对象
function example() {
return { a: 1, b: 2 };
}
let x = example();
console.log(x.a); //1
console.log(x.b); //2
c、提取JSON数据 解构赋值对提取JSON对象中的数据,尤其有用。
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data:number} = jsonData;
console.log(id); //42
console.log(status); //"ok"
console.log(number[1]); //5309
let [a,b] = number;
console.log(a); //867
console.log(b); //5309
d、设置函数参数的默认值,这样传参时缺少参数,会让局部变量使用默认值。
e、遍历Map结构
let map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
// first is hello
// second is world
任何部署了Iterator接口的对象,都可以用for...of循环遍历。
Map结构原生支持Iterator接口,配合变量的解构赋值,获取键名和键值就非常方便。