js 數組解構賦值


Es6中新增了對數組拆分並且賦值的方法——解構賦值

例子:

let arr = [1, 2, 3];
let [a, b, c] = arr;
console.log("a = " + a);// a = 1
console.log("b = " + b);// b = 2
console.log("c = " + c);// c = 3

等式左邊的[a,b,c]和右邊的數組的元素相互對應,a->arr[0],b->arr[1],c->arr[3],可以通過解構的方式來把數組中的元素拆分並且賦值給創建好的變量。

數組解構賦值的特點

  1. 等式左邊的變量個可以超過右邊數組中的元素個數,左邊多余的變量會被賦值為undefined
let [a, b, c] = [1,2];
console.log("a = " + a);// 1
console.log("b = " + b);// 2
console.log("c = " + c);// undefined
  1. 等式左邊的變量個數可以小於右邊數組中的元素個數

let [a, b] = [1,2,3]
console.log("a = " + a); //a = 1
console.log("b = " + b); //b = 2
  1. 左邊變量個數小於右邊數組元素個數時,左邊的等式若是設置了默認值,則會被覆蓋
let [a, b = 9999] = [1, 2, 3];
console.log("a = " + a);// a = 1
console.log("b = " + b);// b = 2

4.左邊變量個數大於右邊數組元素個數時,我們可以給左邊變量指定默認值

let [a, b = 2, c = 3] = [1];
console.log("a = " + a);// a = 1
console.log("b = " + b);// b = 2
console.log("c = " + c);// c = 3
  1. 等式左邊的格式要與右邊的數組一致,才能正常解構

例如:

let [a, b, [c, d]] = [1, 2, [3, 4]];
console.log("a = " + a);// a = 1
console.log("b = " + b);// b = 2
console.log("c = " + c);// c = 3
console.log("d = " + d);// d = 4

能夠成功進行解構

let [a, b, c, d] = [1, 2, [3, 4]];
console.log("a = " + a);// a = 1
console.log("b = " + b);// b = 2
console.log("c = " + c);// c = 3,4
console.log("d = " + d);// undefined

兩邊結構不同,將無法正確地進行完全解構

我們可以用擴展運算符來更加簡便地解構數組

例子:

let [a, ...b] = [1, 2, 3, 4, 5, 6, 7];
console.log(a);	// 1
console.log(b);	// [2, 3, 4, 5, 6, 7]

可以把1之外的所有其他數組元素賦值給b


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM