ES6 允許按照一定模式,從數組和對象中提取值,對變量進行賦值,這被稱為解構(Destructuring)。
一.數組的解構
// const details=['jelly','laver','laverlist.com']; // const[name,website,category]=details; // console.log(name,website,category);//jelly laver laverlist.com // const details=['laver','laverlist.com']; // const[name,website,category='php']=details; // // 當對應的值是undefine時候,才會取默認值,否則就是對應的值 // console.log(name,website,category);//laver laverlist.com php const details=['laver','laverlist.com',null]; const[name,website,category='php']=details; console.log(name,website,category)//laver laverlist.com null let a=10; let b=20; // a和b的值進行交換 [a,b]=[b,a]; console.log(a,b)
注意,ES6 內部使用嚴格相等運算符(===
),判斷一個位置是否有值。所以,只有當一個數組成員嚴格等於undefined
,默認值才會生效。
// let [x=1]=[undefined]; // console.log(x);//undefine let [x=1]=[null] console.log(x);//null
上面代碼中,如果一個數組成員是null
,默認值就不會生效,因為null
不嚴格等於undefined
。
二。對象的解構
const tom={ name:'jonse', age:25, family:{ mother:'a', father:'b', brother:'c' } }; // const name=tom.name; // const age=tom.age; // 解構的改寫 const {name,age}=tom; console.log(name); console.log(age); // const {father,mother,brother}=tom.family; // console.log(father); const father='dad'; const {father:f,mother,brother}=tom.family; console.log(father); // 假如father變量被聲明使用過,你可以給他重新命名 let {foor,bor}={foor:'x',bor:'d'}; console.log(foor)//x // 上面代碼中,等號右邊的對象沒有foo屬性,所以變量foo取不到值,所以等於undefined。 // console.log(foo)//foo is not definedat 解構.html:14
var {x = 3} = {x: undefined}; x // 3 var {x = 3} = {x: null}; x // null
上面代碼中,屬性x
等於null
,因為null
與undefined
不嚴格相等,所以是個有效的賦值,導致默認值3
不會生效。
三。變量的解構賦值用途很多。
(1)交換變量的值
let x = 1; let y = 2; [x, y] = [y, x];
(2)從函數返回多個值
(3)函數參數的定義;解構賦值可以方便地將一組參數與變量名對應起來。
// 參數是一組有次序的值 function f([x, y, z]) { ... } f([1, 2, 3]); // 參數是一組無次序的值 function f({x, y, z}) { ... } f({z: 3, y: 2, x: 1})
(4)提取 JSON 數據
解構賦值對提取 JSON 對象中的數據,尤其有
let jsonData = { id: 42, status: "OK", data: [867, 5309] }; let { id, status, data: number } = jsonData; console.log(id, status, number); // 42, "OK", [867, 5309]
(6)遍歷 Map 結構
任何部署了 Iterator 接口的對象,都可以用for...of
循環遍歷。Map 結構原生支持 Iterator 接口,配合變量的解構賦值,獲取鍵名和鍵值就非常方便。
const map = new Map(); map.set('first', 'hello'); map.set('second', 'world'); for (let [key, value] of map) { console.log(key + " is " + value); } // first is hello // second is world
如果只想獲取鍵名,或者只想獲取鍵值,可以寫成下面這樣。
// 獲取鍵名 for (let [key] of map) { // ... } // 獲取鍵值 for (let [,value] of map) { // ... }