数组的解构赋值(基本语法和定义)

在ES6中按照一定模式,从数组和对象中提取值对变量进行赋值,这被称为解构(Destructuring)

  • 以前,为变量赋值,只能直接指定值

      let a = 'a';
      let b = 'b';
      let c = 'c';
    
  • ES6 允许写成下面这样

      let [a, b, c] = ['a', 'b', 'c']
      console.log(a); //a
      console.log(c); //c
    

这表示,可以从数组中提取值,按照对应位置,对变量赋值

举几个🌰

  •   let [a,[[b],c]] = [1,[[2],3]]
      console.log(a); //1
      console.log(b); //2
      console.log(c); //3
    
  •   let [, , thrid] = ['first', 'second', 'thrid']
      console.log(thrid);//thrid
    
  •   let [a, , c] = [1, 2, 3];
      console.log(a); //1
      console.log(c); //3
    
  •   let [a, ...b] = [1, 2, 3, 4]
      console.log(a); // 1
      console.log(b); // [2,3,4]
    
  •   const [a, b, ...c] = ['a'];
      console.log(a); // a
      console.log(b); // undefined
      console.log(c); // []
    

如果解构不成功,变量值就是undefined

    let [a] = [];
    let [b, c] = [1];
    console.log(a); // undefined
    console.log(b); // 1
    console.log(c); // undefined

或者是不完全解构,就是等号左边的模式,只匹配一部分等号右边的数组,这种情况是可以解构成功

    let [x, y] = [1, 2, 3];
    console.log(x); //1
    console.log(y); //2
    let [a, [b], d] = [1, [2, 3], 4]
    console.log(a); //1
    console.log(b); //2
    console.log(d); //4
如果等号右边不是可以遍历的解构(不具有Iterator接口),就会报错
    //以下全部报错
    let [a] = 1;
    let [a] = false;
    let [a] = NaN;
    let [a] = undefined;
    let [a] = null;
    let [a] = {};

Set结构,也可以使用数组的解构赋值

    let [a, b, c] = new Set(['a', 'b', 'c'])
    console.log(b); // b

事实上,只要数据结构具有Iterator接口,都可以采用数组形式进行结构赋值.

    //fibs是一个Generator函数,原生具有Iterator接口
    function* fibs() {
        let [a, b] = [0, 1];
        while (true) {
            yield a;
            [a, b] = [b, a + b]
        }
    }
    let [first, second, thrid, fourth, fifth, sixth] = fibs();
    console.log(first); // 0
    console.log(sixth); // 5
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。