解构赋值语法是一种JavaScript表达式,可以将数组中的值或对象中的属性解压缩为不同的变量。
不带参数
let a, b, rest;
[a, b] = [10, 20];
console.log(a);
// expected output: 10
console.log(b);
// expected output: 20
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(rest);
// expected output: Array [30,40,50]
好吧,可能还是不够形象
这是原来代码
const user = { name: 'John Doe', age: 34 };
const name = user.name; // name = 'John Doe'
const age = user.age; // age = 34
然后结构赋值后
const { name, age } = user;
// name = 'John Doe', age = 34
按照惯例,来个练习
const HIGH_TEMPERATURES = {
yesterday: 75,
today: 77,
tomorrow: 80
};
// Only change code below this line
const today = HIGH_TEMPERATURES.today;
const tomorrow = HIGH_TEMPERATURES.tomorrow;
// Only change code above this line
答案是
const HIGH_TEMPERATURES = {
yesterday: 75,
today: 77,
tomorrow: 80
};
// Only change code below this line
const {today,tomorrow}=HIGH_TEMPERATURES;
// Only change code above this line
带入参数
使用上一个示例中的相同对象:
const user = { name: 'John Doe', age: 34 };
在分配中给新变量名称的方法如下:
const { name: userName, age: userAge } = user;
// userName = 'John Doe', userAge = 34
小测
const HIGH_TEMPERATURES = {
yesterday: 75,
today: 77,
tomorrow: 80
};
// Only change code below this line
const highToday = HIGH_TEMPERATURES.today;
const highTomorrow = HIGH_TEMPERATURES.tomorrow;
// Only change code above this line
将两个分配替换为等效的解构分配。它仍应从HIGH_TEMPERATURES对象分配变量highToday和highTomorrow today和tomorrow的值。
答案
const HIGH_TEMPERATURES = {
yesterday: 75,
today: 77,
tomorrow: 80
};
// Only change code below this line
const {today:highToday,tomorrow:highTomorrow}=HIGH_TEMPERATURES;
// Only change code above this line
如果是被{}包裹的,用这种写法
const LOCAL_FORECAST = {
yesterday: { low: 61, high: 75 },
today: { low: 64, high: 77 },
tomorrow: { low: 68, high: 80 }
};
// Only change code below this line
const{today:{low:lowToday,high:highToday}}=LOCAL_FORECAST;
// Only change code above this line
要调换a ,b两个
let a = 8, b = 6;
// Only change code below this line
[a,b]=[b,a];
res参数和destructuring参数混合搭配起来的用法
const source = [1,2,3,4,5,6,7,8,9,10];
function removeFirstTwo(list) {
"use strict";
// Only change code below this line
const [a,b,...arr] = list; // Change this line
// Only change code above this line
return arr;
}
const arr = removeFirstTwo(source);