ES6新特性:解构赋值

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

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

let x=1;

let y=2;

let z=3;

ES6允许如下写法

let[x,y,z]=[1,2,3];//模式匹配,按照位置来匹配

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

 

let [x,y,z]=[1,{'x':123},3];

console.log(y);//输出依次是 2 [1,2] {x: 123}

 

let [head,...tail] = [0,1,2,3,4,5,6,7,8,9];  

console.log(head);     //0

console.log(tail);       //[1,2,3,4,5,6,7,8,9]  

 

解构不成功,值都会等于undefined

 


let [x, y] = [1, 2, 3];
x // 1
y // 2 
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4

上面两个案例都属于不完全解构,但可以成功

如果等号右边不是数组,就会报错

 


// 报错 let [foo] = 1; let [foo] = false; let [foo] = NaN; let [foo] = undefined; let [foo] = null; let [foo] = {};

上面的语句都会报错,因为等号右边的值,要么转为对象以后不具备 Iterator 接口(前五个表达式),要么本身就不具备 Iterator 接口(最后一个表达式)。

 

 

解构赋值,允许指定默认值

数组:按照位置来匹配

let [x,y='3',z]=[1];

let [x,y='3',z]=[1,2];

let [x,y='3',z]=[1,2,3];

let [x,y='3',z]=[1,,3];

let [x,y='3',z='4']=[1,,null];

console.log(x,y,z);

//1 3 undefined

//1 2 undefined

//1 2 3

//1 "3" 3

//1 "3" null

 

函数

 

function f(){

  return 'aaa';

};

let[x=f()]=[];

console.log(x);//'aaa'

 

对象 按照对应的名字(属性的名称)来匹配

let{x,y}={x:"1",y:"2"};==let{x:x,y:y}={x:"1",y:"2"} 

x:x 前面的x代表一个匹配模式,后者代表一个变量

console.log(x,y);//这里的x,y为后面的变量  1 2

 

let {x1:qq,y1}={y1:'22',x1:'21'};

console.log(qq);  //21

 

 

let {x1:qq,y1}={y1:'22',x1:'21'};

console.log(x1);//报错

 

 

let {x=1,y}={x:'a'};

console.log(x,y);//a undefined

 

 

let {x : y ='111'}={x : undefined};

console.log(y);//111

 

let {x : y ='111'}={x : null};

console.log(y);//null

 

 

字符串的结构赋值

let [a,b,c,d,e,f]='nodejs';

console.log(b);//o

类似于数组,按照位置赋值

 

 

函数参数的解构赋值

function fun([x,y]){

return x+y;

};

fun([3,5]);//8

function fun([x=0,y=0]){

return x+y;

};

fun([]);

//0

function fun([x=0,y=0]){

return x+y;

};

fun([3,5]);

//8

function fun([x=3,y=5]){

return x+y;

};

fun([]);

//8  

如果调用的时候传值就用次值,否则会直接使用默认值

函数里返回多个值

function fun(){

    return [1,2,3];

}

let [a,b,c]=fun();

console.log(a,b,c);//1,2,3

 

 

//对象

function num(){

let obj={

"name":"str",

"age":12

}

return obj

}

//防止和其他明明的参数冲突,对参数重命名

let [name:wqw,age]=num();

console.log(wqw,age);

let obj={

"name":"str",

"age":12,

"friends":["a1","b1"],

"member":{x:1,y:2}

}

let {name,age,friends:ff,member}=obj;

console.log(ff[1]);//b1

console.log(member.x);//1

用途
(1)交换变量的值

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

上面代码交换变量xy的值,这样的写法不仅简洁,而且易读,语义非常清晰。

 

(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 数据

解构赋值对提取 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]

上面代码可以快速提取 JSON 数据的值。

(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循环遍历。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) {
  // ...
}

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

加载模块时,往往需要指定输入哪些方法。解构赋值使得输入语句非常清晰。


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

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值