对象解构
// 对象结构:
let object = {
name: "lch",
age: 18,
city: "shanghai",
birthday: "1996",
sex: "man",
location: {
from: {
x: 100,
y: 100,
},
to: {
x: 456,
y: 345,
},
},
left: "left",
right: "right",
};
({ left, right } = object); // 解构赋值
const { name, age } = object;
const { city = "fuzhou" } = object; // 给予默认值
const { birthday: myBirthday } = object; // 赋值给本地变量myBirthday
const { sex: mySex = "man" } = object;
const { company = "jd" } = object; // 不存在的变量的默认赋值
const {
location: { from }, //嵌套的结构赋值
} = object;
数组解构
let arr = [
"red",
"blue",
"green",
{
name: "lch",
age: 18,
},
[1, 2, 3],
];
const [firstColor, , thirdColor] = arr; // 按照位置,变量名任意
const [first, ...args] = arr; // 剩余项,使用...语法
const [...cloneArr] = arr; // 可以用于克隆(浅拷贝)
const [, , , , [one, two, three]] = arr; // 对内部数组的解构
const [, , , , , what = "defaultColor"] = arr; // 若不存在默认赋值生效
let a = 1,
b = 2;
[a, b] = [b, a]; // 方便地交换
参数解构
// 参数解构
let object = {
city: "shanghai",
birthday: "1996",
sex: "man",
};
// 通常可能这样
function getMessage(name, age, object) {
let { city, birthday, sex } = object;
console.log(name, age, city, birthday, sex);
}
// 但能修改为
function MygetMessage(name, age, { city, birthday, sex }={}) {
// 通过赋予默认值{},防止未传递object时变为undefined而出错
console.log(name, age, city, birthday, sex);
}
在项目代码中碰到这样的:
function myfn(params){
const {name} = params;
}
myfn({name});
若name为数组,则传入的就是数组的真实地址(其实和直接传入name也没差):
function myfn(params) {
const { arr } = params;
arr[0] = 999;
}
var arr = [1, 2, 3];
myfn({ arr });
console.log(arr); // [999, 2, 3]
用途
(1)交换变量的值
let x = 1;
let y = 2;
[x, y] = [y, x];
(2)从函数返回多个值
// 返回一个对象
function example() {
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();
(3)函数参数的定义
// 参数是一组有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);
// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});
(4)提取JSON数据
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
(5)函数参数的默认值
指定参数的默认值,就避免了在函数体内部再写var foo = config.foo || 'default foo';
这样的语句。
(6)遍历Map结构
任何部署了 Iterator 接口的对象,都可以用for...of
循环遍历。Map 结构原生支持 Iterator 接口,配合变量的解构赋值,获取键名和键值就非常方便。
const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
(7)输入模块的指定方法
const { SourceMapConsumer, SourceNode } = require("source-map");