es6 語法 (解構賦值)
{
let a,b,c;
[a,b] = [1,2];
console.log(a,b); //1,2
}
{
let a,b,rest;
[a,b,...rest] = [1,2,3,4,5,6];
console.log(a,b,rest); //3,[4,5,6]
}
2.物件結構賦值
{
let a,b;
({a,b} = {a:1,b:2});
console.log(a,b); //1,2
}
3.預設值
{
let a,b,c,rest;
[a,b,c=3] = [1,2];
console.log(a,b,c); // 1,2,3
}
4.變數交換
{
let a =1;
let b =2;
[a,b] = [b,a];
console.log(a,b); //2,1
}
5.函式賦值
{
function f(){
return [1,2]
}
let a,b;
[a,b] = f();
console.log(1,2); // 1,2
}
6.選擇性接受值
{
function f(){
return [1,2,3,4,5]
}
let a,b,c;
[a,,,b] = f();
console.log(a,b); //1,4
}
7.第一個取出來,其他的賦值給陣列
{
function f(){
return [1,2,3,4,5]
}
function ff(){
return [1,2,3,4,5]
}
let a,b,c;
let a1,b1,c1;
[a,...b] = f();
[a1,,...b1] = ff();
console.log(a,b); //1,[2,3,4,5]
console.log(a1,b1);1,2,[3,4,5]
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//物件解構賦值
{
let o = {p:42,q:true};
let{p,q} = o;
console.log(p,q); //42,true
}
//物件解構賦值預設值處理
{
let {a=10,b=5} = {a:3};
console.log(a,b); //3,5
}
//物件json 賦值
{
let metaData = {
title:'abc',
test:[{
title:'test',
desc:'description'
}]
}
let {title:esTitle,test:[{title:cnTitle}]} = metaData;
console.log(esTitle,cnTitle) //abc,test
}
更多專業前端知識,請上 【猿204