Blogger Information
Blog 20
fans 0
comment 1
visits 13091
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
解构赋值及其在函数传参中的应用
zg的php学习
Original
861 people have browsed it

解构赋值

将一个多值变量(数组、对象)的值分解赋值给各个单值变量
常规用法:

  1. let name, sex, age;
  2. //数组
  3. let arr = ["张三", "male", 32];
  4. name = arr[0];
  5. sex = arr[1];
  6. age = arr[2];
  7. //对象
  8. let user = { name: "张三", sex: "male", age: 32 };
  9. name = user.name;
  10. sex = user.sex;
  11. age = user.age;

解构用法:

  1. //数组解构
  2. [name, sex, age] = ["张三", "male", 32];
  3. //对象解构
  4. ({ name, sex, age } = { name: "张三", sex: "male", age: 32 });

解构出现参数不足或过多时的解决方法,以数组为例(对象同样)

  1. //参数不足时,可以添加默认值
  2. [name, sex, age = 18] = ["张三", "male"];
  3. //参数过多时,可以使用 “...” 合并参数
  4. [name, sex, age, ...args] = ["张三", "male", 32, "admin@php.cn",32]

注意点:

  • 解构时左右两边的类型必须一致。
  • 对象解构时,因为左边不能直接使用{…},所以当没有 let 关键字时,可以用小括号将整条语句包住,让它成为一个表达式即可。

解构赋值在做为函数参数时的应用

数组或对象做为函数参数传递时的常规用法,以对象为例:

  1. //常规用法
  2. let obj = { name: "张三", sex: "male", age: 32 };
  3. let f = (o) => console.log(o.name, o.sex, o.age);
  4. f(obj);
  1. //解构赋值法
  2. let obj = { name: "张三", sex: "male", age: 32 };
  3. let f = ({ name, sex, age }) => console.log(name, sex, age);
  4. f(obj);

当参数不足或过多时,同样可以使用添加默认值和”…”合并参数来解决。

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post