1. 程式人生 > >JS ES6的變量的結構賦值

JS ES6的變量的結構賦值

req style fir 語句 多個 cti turn 清晰 rst

變量的結構賦值用戶很多

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‘);

JS ES6的變量的結構賦值