Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
将一个多值变量(数组、对象)的值分解赋值给各个单值变量
常规用法:
let name, sex, age;
//数组
let arr = ["张三", "male", 32];
name = arr[0];
sex = arr[1];
age = arr[2];
//对象
let user = { name: "张三", sex: "male", age: 32 };
name = user.name;
sex = user.sex;
age = user.age;
解构用法:
//数组解构
[name, sex, age] = ["张三", "male", 32];
//对象解构
({ name, sex, age } = { name: "张三", sex: "male", age: 32 });
解构出现参数不足或过多时的解决方法,以数组为例(对象同样)
//参数不足时,可以添加默认值
[name, sex, age = 18] = ["张三", "male"];
//参数过多时,可以使用 “...” 合并参数
[name, sex, age, ...args] = ["张三", "male", 32, "admin@php.cn",32]
数组或对象做为函数参数传递时的常规用法,以对象为例:
//常规用法
let obj = { name: "张三", sex: "male", age: 32 };
let f = (o) => console.log(o.name, o.sex, o.age);
f(obj);
//解构赋值法
let obj = { name: "张三", sex: "male", age: 32 };
let f = ({ name, sex, age }) => console.log(name, sex, age);
f(obj);
当参数不足或过多时,同样可以使用添加默认值和”…”合并参数来解决。