1.基本用法json
{ let a,b; [a,b] = [1,2]; console.log(a, b); // 1 2 } { let a,b,c; [a,b,...c] = [1,2,3,4,5,6]; console.log(a, b, c); // 1 2 [3,4,5,6] } { let a,b,c; [a,b,c=3] = [1,2]; // 設置默認值 console.log(a, b, c); // 1 2 3 }
2.變量交換數組
{ let a = 1; let b = 2; [a, b] = [b, a]; console.log(a, b); // 2 1 }
3.函數返回結果賦值函數
{ function f() { return [true, false]; } let a,b; [a, b] = f(); console.log(a, b); // true false }
4.忽略某些返回值,只取須要的code
{ function f() { return [1,2,3,4,5]; } let a,b; [a,,,b] = f(); console.log(a, b); // 1 4 }
5.函數返回結果不肯定,只關心第n個,剩餘的賦值到一個數組對象
{ function f() { return [1,2,3,4,5]; } let a,b; [a,...b] = f(); console.log(a, b); // 1 [2,3,4,5] }
1.基本用法ip
{ let obj = {p: 42, q: true}; // 變量名要和屬性名一致對應,變量名等於屬性名 // 左側是一個對象,右側也是一個對象 let {p, q} = obj; console.log(p, q); // 42 true } { let {a=10, b=5} = {a:3}; // 設置默認值 console.log(a, b); // 3 5 }
2.json數據的解構賦值it
{ let data = { title: 'hahaha', test: [ { title: 'yoyoyo', desc: 'description' } ] }; let {title: mainTitle, test: [{title: subTitle}]} = data; console.log(mainTitle, subTitle); // hahaha yoyoyo }