变量的解构赋值

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

一.数组的解构

//  const details=['jelly','laver','laverlist.com'];
        // const[name,website,category]=details;
        // console.log(name,website,category);//jelly laver laverlist.com
        // const details=['laver','laverlist.com'];
        // const[name,website,category='php']=details;
        //  // 当对应的值是undefine时候,才会取默认值,否则就是对应的值
        // console.log(name,website,category);//laver laverlist.com php
        const details=['laver','laverlist.com',null];
        const[name,website,category='php']=details;
        console.log(name,website,category)//laver laverlist.com null
        let a=10;
        let b=20;
        // a和b的值进行交换
        [a,b]=[b,a];
        console.log(a,b)

注意,ES6 内部使用严格相等运算符(===),判断一个位置是否有值。所以,只有当一个数组成员严格等于undefined,默认值才会生效。

    // let [x=1]=[undefined];
        // console.log(x);//undefine
        let [x=1]=[null]
        console.log(x);//null

上面代码中,如果一个数组成员是null,默认值就不会生效,因为null不严格等于undefined

二。对象的解构

const tom={
            name:'jonse',
            age:25,
            family:{
                mother:'a',
                father:'b',
                brother:'c'
            }
        };
        // const name=tom.name;
        // const age=tom.age;
        // 解构的改写
        const {name,age}=tom;
        console.log(name);
        console.log(age);       
        // const {father,mother,brother}=tom.family;
        // console.log(father);
        const father='dad';
        const {father:f,mother,brother}=tom.family;
        console.log(father);
        // 假如father变量被声明使用过,你可以给他重新命名
        let {foor,bor}={foor:'x',bor:'d'};
        console.log(foor)//x
        // 上面代码中,等号右边的对象没有foo属性,所以变量foo取不到值,所以等于undefined。
        // console.log(foo)//foo is not definedat 解构.html:14
var {x = 3} = {x: undefined};
x // 3

var {x = 3} = {x: null};
x // null

上面代码中,属性x等于null,因为nullundefined不严格相等,所以是个有效的赋值,导致默认值3不会生效。

三。变量的解构赋值用途很多。

(1)交换变量的值

let x = 1;
let y = 2;

[x, y] = [y, x];

(2)从函数返回多个值

(3)函数参数的定义;解构赋值可以方便地将一组参数与变量名对应起来。

// 参数是一组有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);

// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1})

(4)提取 JSON 数据

解构赋值对提取 JSON 对象中的数据,尤其有

let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};

let { id, status, data: number } = jsonData;

console.log(id, status, number);
// 42, "OK", [867, 5309]

(6)遍历 Map 结构

任何部署了 Iterator 接口的对象,都可以用for...of循环遍历。Map 结构原生支持 Iterator 接口,配合变量的解构赋值,获取键名和键值就非常方便。

const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');

for (let [key, value] of map) {
  console.log(key + " is " + value);
}
// first is hello
// second is world

如果只想获取键名,或者只想获取键值,可以写成下面这样。

// 获取键名
for (let [key] of map) {
  // ...
}

// 获取键值
for (let [,value] of map) {
  // ...
}
原文地址:https://www.cnblogs.com/wanqingcui/p/10801403.html