瞅瞅ES6多好玩——解构赋值篇

解构赋值:按照一个数据值的结构,快速解析获取到其中的内容

  • 数组解构赋值

    1.想要几个就几个
    let ary = [12, 23, 34, 45, 56];
    let [a, b, c] = ary;
    console.log(a, b, c);  // 12 23 34
    let [d] = ary;
    console.log(d);        // 12
    
    // 省略赋值
    let [e, , f] = ary;
    console.log(e,f);      // 12 34
    
    2.设置默认值也行(默认解构)
    let ary = [12];
    let [a, b = 0] = ary;
    console.log(a, b);     // 12 0
    
    3.不仅可以解构成单个值,还可以返回个数组
    let ary = [12, 23, 34, 45, 56];
    let [a, ...b] = ary;
    console.log(a, b);         // 12 [23,34,45,56]
    let [a, ...b, c] = ary;    // SyntaxError: Rest element must be last element
    
    4.互换位置更加方便
    let a = 12,
        b = 13;
    [a, b] = [b, a];
    console.log(a, b);    // 13 12
    
  • 对象解构赋值

    1.对象解构赋值默认情况下要求:左侧变量名和对象中的属性名一致才可以
    let obj = {name: 'xxx', age: 25, sex: 0};
    let {name, age} = obj;
    console.log(name, age);  // "xxx" 25
    
    2.给不存在的属性设置默认值
    let obj = {name: 'xxx', age: 25, sex: 0};
    let {friend = 0} = obj;
    console.log(friend);    // 0 
    
    3.给解构的属性名起别名作为需要使用的变量
    let obj = {name: 'xxx', age: 25, sex: 0};
    let {age: ageAA} = obj;
    console.log(age);    // Uncaught ReferenceError: age is not defined
    console.log(ageAA);  // 25
    

你可能感兴趣的:(瞅瞅ES6多好玩——解构赋值篇)