一、对象解构
解构是有用的,它允许你在一行代码中进行操作,否则可能需要多行代码
let rect = { width: 100, height: 200 }
//解构
let { width, height } = rect;
console.log(width, height); //100,200
rect.width = 300;
{ width, height } = rect; //使用括号,分配给现有变量
console.log(width, height) //300,200
如果要将提取的变量分配给新的变量名称
//结构
let obj = { width: 200, height:300 };
//解构
let { value: width } = obj;
console.log(value); //200
此外,你还可以使用解构从结构中获取更深层次的数据
let foo = { bar: { bas: 123 } };
let { bar: { bas } } = foo; //有效的 let bas = foo.bar.bas;
在对象中使用rest
通过使用解构和rest,你可以从一个对象中选择任意数量的元素,也可以获取剩余元素组成的对象
let { x, y, ...remaining } = { x:1, y: 2, z: 3, w: 4 }
console.log(x, y, remaining) // 1 2 { z: 3, w:4 }
一个常见的用例是忽略某些属性
//typescript
function goto(point2D: { x: Number, y: Number }) {
//想象一些可能有破坏性的代码
//如果你传入一些比预期的成员多的对象
}
// 从其他地方获取的数据
const point3D = { x: 1, y: 2, z: 3 };
// 使用rest删除其他成员
const { z, ...point2D } = point3D;
goto(point2D)
二、数组解构
如何实现在不使用第三个变量的情况下交换两个变量
let x = 1, y = 2;
[x, y] = [y, x];
x //2
y //1