ES6解构赋值理解及用途

解构

是一种JavaScript表达式,可让你从数组,对象,映射和集合中提取数据到它们自己的变量中。它允许你一次从多个对象中提取对象的属性或从数组中提取项目。

const user = {
    name: 'Lucy',
    age: 18,
    gender: 'W',
    member:true
}
const name=user.name;
const member=user.member;
//通过解构
const {name, age, gender, member } = user;
console.log(name);//Lucy
console.log(member);//true

解构赋值  用途

(1)交换变量的值

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

(2)从函数返回多个值

//返回一个数组
function example(){
   return [1,2,3];
}
let [a,b,c]=example();

//返回一个对象
function example(){
    return {
        foo:1,
        bar:2
    };
}
let {foo,bar}=example();

(3)函数参数的定义

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

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

(4)提取JSON数据----重要

let jsonData={
    id:42,
    status:"OK",
    data:[864,5320]
};
let {id,status,data:number}=jsonData;
console.log(id,status,number);
//42,OK,[864,5320]

(5)函数参数的默认值

jQuery.ajax=function(url,{
    async=true,
    beforeSend=function(){},
    cache=true,
    complete=function(){},
    crossDomain=false,
    global=true,
    //...more config
}={}){
    //... do stuff
};

            指定参数的默认值,避免了函数体内部写var foo = config.foo || 'default foo';

(6)遍历Map结构

             任何部署了Iterator接口的对象,都可以用for...of循环遍历

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){
    //...
}

(7)输入模块的指定方法

const {SourceMapConsumer,SourceNode } = require("source-map");

 

 

 

 

 

 

 

 

 

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值