天天看點

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

文中有錯誤的地方希望指出,共同進步

繼續閱讀