什么是解構
destructuring:百度百科的意思是結構分解,ES6 中允許按照一定模式,從數組和對象中提取值,對變量進行賦值,這被稱為解構(Destructuring)。
開發中比較常見的有對象解構、 數組解構、混合解構。這是一種將數據結構分解為更小的部分的過程,從而達到簡化提取信息的目的。
對象解構
傳統方法獲取對象中的值
let node = {
type: 'Identifier',
name: 'foo'
}
console.log(node.type) // Identifier
console.log(node.foo) // foo
使用解構
let node = {
type: 'Identifier',
name: 'foo'
}
let { type, name } = node
console.log(type) // Identifier
console.log(name) // foo
如果指定的局部變量名稱在對象中不存在,那么這個局部變量會被賦值為undefined
let { type, name, value } = node
console.log(type) // Identifier
console.log(name) // foo
console.log(value) // undefined
當指定的屬性不存在時,可以給不存在的屬性定義任意的默認值
let { type, name, value = true } = node
console.log(type) // Identifier
console.log(name) // foo
console.log(value) // true
指定新的變量名進行解構賦值
let arr = {
six: '男',
age: 19
}
let {six:newSix, age:newAge} = arr
console.log(six, age) // six is not defined
console.log(newSix, newAge) // 男 19
看上面是不是覺得很奇怪,傳統對象賦值都是左邊四屬性,右邊是值。但是在解構寫法中右邊是屬性,左邊是值,所以新的變量名在右邊。
- 如果使用let、var、const對對象進行解構時,被解構對象的值不能不存在。
- 不使用var、let、const賦值時,需要將解構語句使用()進行包裹
({type,name} = node);//{}在js中作為代碼塊,單獨使用加等號會報錯會報錯
-
嵌套對象解構
在對象嵌套對象中解構,我們會在第一層解構中繼續使用花括號來深入下一層進行查找;我們先來看一個栗子:
let node = {
type: "Identifier",
name: "foo",
loc: {
start: {
line: 1,
column: 1
},
end: {
line: 1,
column: 4
}
}
}
上面是一個嵌套對象node,我們先解構第一層
let { loc, type, name } = node // {} Identifier foo
可以看到我們特意打亂了{}中屬性的順序,結果仍然正確輸出,所以可以猜到具體的對應方式應該是根據名字來對應的,和順序無關。
繼續解構第二層
let { loc: { start }} = node;
console.log(start.line); // 1
console.log(start.column); // 4
此處我們也可以將start賦值給一個新的自定義的局部變量,假設我們賦值給newStart
let { loc: { start: newStart }} = node
console.log(newStart.line) // 1
console.log(newStart.column) // 4
總結如下:
所有冒號前的標識符都代表在對象中的檢索位置,其右側為被賦值的變量名;如果冒號后是花括號,則意味著要賦予的最終值嵌套在對象內部更深的層級中。
數組解構
數組解構使用的是數組字面量,且解構操作全部在數組內完成,并且數組解構不需要像對象字面量語法一樣使用對象的命名屬性。
let colors = [ 'red', 'green', 'blue' ]
let [ firstColor, secondColor ] = colors
console.log(firstColor) // 'red'
console.log(secondColor) // 'green'
數組解構語法中,我們主要是通過值在數組中的位置進行選取,且可以將其存儲在任意變量中,未顯示聲明的元素會被直接忽略。
let [ , , thirdColor ] = colors
console.log(thirdColor) // 'blue'
-
數組解構之變量交換
傳統ES5中互換值一般需要引入第三個臨時變量作為中轉,但如果使用數組解構賦值語法,就不需要在增加額外變量了。
// ES5中互換值:
let a = 1, b = 2, tmp;
tmp = a
a = b
b = tmp
console.log(a, b) // 2, 1
// ES6中互換值
let a = 1, b = 2;
[ a, b ] = [b, a]
console.log(a, b) // 2, 1
-
嵌套數據解構
let colors = [ 'red', [ 'green', 'lightgreen'], 'blue' ]
let [ firstColor, [ secondColor, thirdColor ], fourthColor ] = colors
console.log(firstColor) // red
console.log(secondColor) // green
console.log(thirdColor) // lightgreen
console.log(fourthColor) // blue
-
默認值
也可以在數組解構賦值表達式中為數組中的任意位置添加默認值,當指定位置的屬性不存在或其值為undefined時使用默認值
let colors = [ 'red' ]
let [ firstColor, secondColor = 'green' ] = colors
console.log(firstColor) // red
console.log(secondColor) // green
-
不定元素
...為展開運算符我們應該都知道它的用途,操作數組時可以用來把數組展開成字符串。在數組解構中,可以通過...語法將數組中的其余元素賦值給一個特定的變量。
let colors = [ 'red', 'green', 'blue' ]
let [ firstColor, ...restColors ] = colors
console.log(firstColosr) // 'red'
console.log(restColors.length); // 2
console.log(restColors[0]); // "green"
console.log(restColors[1]); // "blue"
-
數組復制
在ES5中,開發者們經常使用concat()方法來克隆數組
var colors = [ "red", "green", "blue" ];
var clonedColors = colors.concat();
console.log(clonedColors); //"[red,green,blue]"
concat()方法的設計初衷是連接兩個數組,如果調用時不傳遞參數就會返回當前函數的副本
在ES6中,可以通過不定元素的語法來實現相同的目標
let colors = [ "red", "green", "blue" ];
let [ ...clonedColors ] = colors;
console.log(clonedColors); //"[red,green,blue]"
在被解構的數組中,不定元素必須為最后一個條目,在后面繼續添加逗號會導致程序拋出語法錯誤。
-
混合解構
let err = {
errors: [
{
msg: 'this is a message'
},
{
title: 'this is a title'
}
]
}
上面的代碼中,err對象中包含errors,errors又是一個數組又包含新的對象,提取對象中的msg。我們可以將上述栗子一步一步拆開進行解構:
let { errors } = err
let [ firstArr ] = errors
let { msg } = firstArr
console.log(msg) // 'this is a message'
也可以這樣解構
let [ , { title }] = err.errors
console.log(title) // 'this is a title'
let [{ msg }] = err.errors
console.log(msg) // 'this is a message'
來看一個更復雜一點的,其實只要會找順序,這個理解起來還是很簡單的。
let node = {
type: "Identifier",
loc: {
start: {
line: 1,
column: 1
}
},
range: [0, 3]
};
let {
loc: { start },
range: [ startIndex ]
} = node;
console.log(start.line); // 1
console.log(start.column); // 1
console.log(startIndex); // 0
實際使用- 參數解構
一般用在封裝函數參數的情況,如下栗子:
// options 上的屬性表示附加參數
function setCookie(name, value, options) {
options = options || {};
let secure = options.secure,
path = options.path,
domain = options.domain,
expires = options.expires;
// 設置 cookie 的代碼
}
//可以改寫為:對options進行解構并賦予默認值
function setCookie(name, value, { secure, path, domain, expires } = {}) {
// ...
}