对象解构
解构本质上是匹配,只要等号两边的模式相同,左边的变量就会被赋予对应的值。
解构的目标需为可遍历对象
可以重新命名,可以默认值
const obj = {
name:'A',
age:18,
address:'B'
}
const {name,age,address} = obj;
console.log(name)//'A'
let [a = 3, b = a] = []; // a = 3, b = 3
let [a = 3, b = a] = [1]; // a = 1, b = 1
let [a = 3, b = a] = [1, 2]; // a = 1, b = 2
用于函数参数默认值
function drawES5Chart(options) {
options = options === undefined ? {} : options;
var size = options.size === undefined ? 'big' : options.size;
var cords = options.cords === undefined ? { x: 0, y: 0 } : options.cords;
var radius = options.radius === undefined ? 25 : options.radius;
console.log(size, cords, radius);
// now finally do some chart drawing
}
drawES5Chart({
cords: { x: 18, y: 30 },
radius: 30
});
解构语法别名是冒号,赋值是等号
使用解构:
function drawES6Chart({size='big',cords={x:10,y:30},radius:30}={})
{
console.log(size,cords,radius)
}
drawES5Chart({
cords: { x: 18, y: 30 },
radius: 30
});
交换变量的值
let x = 4
let y = 6
[x,y] = [y,x]