ES6 解构赋值 和 剩余参数

1. 解构分为解构数组和解构对象

参考 https://www.runoob.com/w3cnote/deconstruction-assignment.html 【仅作为个人学习转载记录】

2. 结合 剩余参数 代码示例:

  // 解构数组
  let arr = ['blue', 'pink', 'green'];
  let [blue, pink, green] = arr;
  console.log(blue); // blue
  console.log(green); // green
  console.log(pink); // pink
// 剩余参数 形式: ...+自定义参数名 如下:...args function args_func(num1, ...args) { console.log(num1); // 1 console.log(args); // [2, 3, 4, 5] } args_func(1,2,3,4,5); // 解构数组与剩余参数相结合方式使用 let [blue_, ...color_args] = arr; console.log(blue_); // 因为上面定义了blue,因此这里使用blue_区分,返回值为blue console.log(color_args); // ['pink', 'green']

 

————————————————————————————————————————————————————————————————————————————————————————————

09-13新补充:https://es6.ruanyifeng.com/#docs/destructuring#%E6%95%B0%E7%BB%84%E7%9A%84%E8%A7%A3%E6%9E%84%E8%B5%8B%E5%80%BC

  let [a, b, c] = [1, 2, 3];
  console.log(a, b, c); // 1 2 3
  let [a, b] = [1, 2, 3];
  console.log(a, b); // 1 2
  let [a, b, c, d] = [1, 2, 3];
  console.log(a, b, c, d); // 1 2 3 undefined
  /* ES6中对于空值的判断:只有严格等于(===)undefined,才会被认为空值 */
  let [a,b,c] = [1,2,undefined];
  console.log(a, b, c); // 1 2 undefined
  let [a,b,c] = [1,2,null];
  console.log(a, b, c); // 1 2 null
ES6 允许解构赋值:属于模式匹配,即等号两边格式相等,则左边的变量会被赋予右边对应位置的值
用途:1. 交换变量的值
2. 从函数返回多个值
3. 函数参数的定义
4. 提取json数据
5. 指定参数的默认值
6. 便于加载模块中的方法
7. 便于遍历Map结构
posted @ 2021-08-09 17:43  TwinkleG  Views(229)  Comments(0)    收藏  举报