JS ES6的变量的结构赋值

变量的结构赋值用户很多

1、交换变量的值

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

上面的代码交换变量x和变量y的值,这样的写法不仅简洁,易读,语义非常清晰

 

2、从函数返回多个值

函数只能返回一个值,如果要返回多个值,只能讲他们放在数组或者对象里返回。了解解构赋值,取值这些值非常方便

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

 

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

 

3、函数参数的定义

解构赋值可以方便的讲一组参数与变量名对应起来。

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

 

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

 

4、提取JSON数据

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

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

 

5、函数参数的默认值

、、、

 

6、遍历Map结构

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

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

for(let [key,value] of map){
    console.log(key,value);
}

//first hello
//second world


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

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

//first
//second

//获取键值
for(let [,value] of map){
    console.log(value);
}
//hello
//world

 

7、输入模块的指定方法

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

const {a,b} = require('source-map');

 

posted @ 2018-07-09 23:41  saucxs  阅读(5943)  评论(0编辑  收藏  举报