ES6_析构赋值(Destructuring Assignment)
析构赋值——对象篇
《一》使用析构赋值从对象中提取相应的值赋给相同变量名的变量:const { today, tomorrow }=LOCAL_FORECAST;
《二》使用析构赋值从对象中提取相应的值赋给相同变量名的变量,然后将变量名更改,使其与对象里的变量名不相同:const { today:newToday, tomorrow:newTomorrow }=LOCAL_FORECAST;
《三》使用析构赋值从嵌套对象中赋值变量:
const LOCAL_FORECAST = {
yesterday: { low: 61, high: 75 },
today: { low: 64, high: 77 },
tomorrow: { low: 68, high: 80 }
};
const {today:{low:lowToday,high:highToday}}=LOCAL_FORECAST;
/*
//测试:
console.log(low); //ReferenceError: low is not defined
console.log(today.low); //ReferenceError: today is not defined
console.log(LOCAL_FORECAST.today.low); //64
console.log(LOCAL_FORECAST.today.lowToday); //undefined
console.log(today.lowToday); //ReferenceError: today is not defined
console.log(lowToday); //64
*/
析构赋值——数组篇
与扩展操作符不用的是,析构数组可以选择单个元素赋值给变量。
PS:扩展操作符‘...’会将数组的所有元素解包为以逗号分隔的列表。
//例一:
const [a, b] = [1, 2, 3, 4, 5, 6];
console.log(a, b); //1,2
//例二:
const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
console.log(a, b, c); //1,2,5
如上所示,默认按顺序分配元素值给变量。还可以使用逗号访问数组中任何索引处的值(即用逗号代替不想要的元素值,一直‘逗’到想要的元素位置),并进行解构以达到所需的索引。
例三:
let a = 8, b = 6;
//使用解构赋值交换a和b的值:
[a, b] = [b, a];
//测试:
console.log(a,b); //6 8
例四:
目的:通过剩余参数将析构赋值做出一个等效于Array.prototype.slice()的结果,从而使arr是原始数组源的省略前两个元素的子数组。
代码:
const source = [1,2,3,4,5,6,7,8,9,10];
function removeFirstTwo(list) {
const [a,b,...arr] = list; //arr表示原始数组源的子数组。a,b表示取前两个元素赋给a、b,即省略前两个元素,将剩下的元素赋值给arr。
return arr;
}
//测试:
const arr = removeFirstTwo(source);//由于上面的arr是定义在函数里的,故只作用在函数范围内。这里的arr是函数外定义的,故不会报错。
console.log(arr); //[ 3, 4, 5, 6, 7, 8, 9, 10 ]