学习ES6,白菜打卡第一天

348 阅读1分钟

1. 数组的解构赋值

基本用法:
    let [a , b , c] = [1, 2, 3]
    console.log(a);//1
  
    let [head,...foot] = [1,2,3,4,5]
    console.log(head);//1
    console.log(foot);//[2,3,4,5]
    
    let [a, [b], d] = [1, [2, 3], 4];
    console.log(b);//2
    
    let [a, [...b], d] = [1, [2, 3], 4];
    console.log(b);//[2,3]
默认值:
    let [foo = true] = [];
    console.log(foo);//true
    
    ES6 内部使用严格相等运算符(`===`),判断一个位置是否有值。
    所以,只有当一个数组成员严格等于`undefined`,默认值才会生效。
    
    let [x, y = 'b'] = ['a', undefined];
    console.log(x,y); // x='a', y='b'
    
    如果一个数组成员是`null`,默认值就不会生效,因为`null`不严格等于`undefined`let [x = 1] = [null];
    x // null
    
    function f() {
      console.log('aaa');
    }
    let [x = f()] = [1];
    console.log(x);//1
    上面代码中,因为`x`能取到值,所以函数`f`根本不会执行。上面的代码其实等价于下面的代码。

    let x;
    if ([1][0] === undefined) {
      x = f();
    } else {
      x = [1][0];
    }
    ps:[1]看成一个数组a,a[0]=1,取第一个值

    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: y is not defined