來(lái)源:前端全棧君丶 發(fā)布時(shí)間:2018-12-04 13:59:53 閱讀量:1457
變量的結(jié)構(gòu)賦值用戶(hù)很多
1、交換變量的值
let x = 1;
let y = 2;
[x,y] = [y,x]
1
2
3
上面的代碼交換變量x和變量y的值,這樣的寫(xiě)法不僅簡(jiǎn)潔,易讀,語(yǔ)義非常清晰
2、從函數(shù)返回多個(gè)值
函數(shù)只能返回一個(gè)值,如果要返回多個(gè)值,只能講他們放在數(shù)組或者對(duì)象里返回。了解 解構(gòu)賦值 ,取值這些值非常方便
//返回一個(gè)數(shù)組
function example(){
return [1,2,3];
}
let [a,b,c] = example();
[a,b,c]; //[1,2,3]
//返回一個(gè)對(duì)象
function example(){
return {
foo:1,
bar:2
};
}
let {foo,bar} = example();
foo; //1
bar; //2
//前端全棧學(xué)習(xí)交流圈:866109386
//面向1-3經(jīng)驗(yàn)?zāi)昵岸碎_(kāi)發(fā)人員
//幫助突破技術(shù)瓶頸,提升思維能力
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
3、函數(shù)參數(shù)的定義
解構(gòu)賦值可以方便的講一組參數(shù)與變量名對(duì)應(yīng)起來(lái)。
//參數(shù)是一組有次序的值
function f([x,y,z]){
console.log(x,y,z);
}
f([1,2,3]); //1,2,3
//參數(shù)是一組無(wú)次序的值
function func({x,y,z}){
console.log(x,y,z);
}
func({z:3,y:2,x:1}); //1,2,3
1
2
3
4
5
6
7
8
9
10
4、提取JSON數(shù)據(jù)
解構(gòu)賦值對(duì)提取JSON對(duì)象中的數(shù)據(jù)尤其有用
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]
1
2
3
4
5
6
7
8
5、函數(shù)參數(shù)的默認(rèn)值
、、、
6、遍歷Map結(jié)構(gòu)
任何部署了Iterator接口的對(duì)象都可以使用for… of循環(huán)遍歷。Map結(jié)構(gòu)原生支持Iterator接口,配合變量的解構(gòu)賦值獲取名和鍵值就非常方便。
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
1
2
3
4
5
6
7
8
9
10
如果只想獲取鍵名,或者只想獲取鍵值,可以這樣寫(xiě)。
//獲取鍵名
for(let [key] of map){
console.log(key);
}
//first
//second
//獲取鍵值
for(let [,value] of map){
console.log(value);
}
//hello
//world
---------------------
在線(xiàn)
客服
服務(wù)時(shí)間:周一至周日 08:30-18:00
選擇下列產(chǎn)品馬上在線(xiàn)溝通:
客服
熱線(xiàn)
7*24小時(shí)客服服務(wù)熱線(xiàn)
關(guān)注
微信
關(guān)注官方微信