解构
是一种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");