码迷,mamicode.com
首页 > 其他好文 > 详细

ES6 Destructurning--解构destructure笔记

时间:2016-08-19 14:38:57      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

解构:先把右面转化成对象

  

  1.数组解构:看位置,两边数组对应位置赋值,对应没有的undefined[有序、一一对应]

let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3

let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]

  默认值,类似于typescript,变量赋值语句,当对应值为undefined时默认值生效(null值会赋值,默认值不生效)

let [x = 1, y = x] = [];     // x=1; y=1
let [x = 1, y = x] = [2];    // x=2; y=2
let [x = 1, y = x] = [1, 2]; // x=1; y=2
let [x = y, y = 1] = [];     // ReferenceError

  2.对象解构赋值[无序,属性相同赋值]

//模式:变量
//模式foo为对应对象的属性,赋值后模式不会被赋值
//变量baz获取变量对应属性的值
var { foo: baz } = { foo: "aaa", bar: "bbb" };
baz // "aaa"
foo // error: foo is not defined

  3.字符串解构赋值--字符串被解析成类似数组的结果

const [a, b, c, d, e] = ‘hello‘;
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"

  4.数值和Boolean值结构,右面值转换为对象(prototype),对应的模式属性的值即为变量

    let {a: s} = 123;
    console.log(s === Number.prototype.a)//true
    let {b: s} = true;
     console.log(s === Boolean.prototype.b)// true

  5.函数解构

//参数为对象,对对象进行结构,如解构失败则设置默认值
function move({x = 0, y = 0} = {}) {
  return [x, y];
}

move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]


//参数指定默认值,x,y为形参,为x,y设置默认值
function move({x, y} = { x: 0, y: 0 }) {
  return [x, y];
}

move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); // [0, 0]

  

 

ES6 Destructurning--解构destructure笔记

标签:

原文地址:http://www.cnblogs.com/carlyin/p/5787319.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!