1. 數組解構 使用方括號[]
-
1.1 交換變量
let a = 1; let b = 2; let c = 3; [a, b, c] = [c, b, a]; console.log(a); // 3 console.log(b); // 2 console.log(c); // 1
-
1.2 訪問數組中的元素
const arr = [,3]; const [a = '1'] = arr; const [, b = '2'] = arr; console.log(a); // 1 console.log(b); // 3
2. 對象解構 使用花括號{}
-
將對象內部屬性提取到外部變量
const obj = {a: 1, b: 2}; const {a, b} = obj; console.log(a); // 1 console.log(b); // 2
function add({a, b}) { return a+b; } let res = add({a: 1, b:2}); console.log(res); // 3
注意:
如果花括號在等式的右邊,那麼你正在聲明一個對象
const obj = { a: 1, b: 2 }
如果花括號在等式左邊,那麼你正在解構一個對象
const { res } = obj;
如果屬性名稱與對象中的變量名稱相同,可以使用屬性簡寫:
// 這裏寫兩遍 name const name = 'Michael' const person1 = { name: name } // 對象屬性簡寫 const person2 = { name }
3. 數組解構和對象解構的區別
- 數組使用
[]
; 對象使用{}
- 對象具有屬性名稱,解構時需使用這些屬性名稱
- 數組按順序排列解構
4. ...
運算符
-
展開(擴展)運算符(Spread)
展開運算符用於取出參數對象中的所有可遍歷屬性,拷貝到當前對象之中;如果用於數組,數組裏面的所有對象都是基礎數據類型,將所有基礎數據類型重新拷貝到新的數組中。
const arr1 = [1,2,3,4] console.log([...arr1, 4,5,6]) // [1, 2, 3, 4, 4, 5, 6] console.log([ 4,...arr1,5,6]) // [4, 1, 2, 3, 4, 5, 6]
如果用於對象,則同名屬性會被覆蓋
const obj1 = {d:4, a:1, b:2 } console.log({...obj1, c:3, d:4}) // {d: 4, a: 1, b: 2, c: 3} console.log({ c:3,...obj1, d:4}) // {c: 3, d: 4, a: 1, b: 2}
展開運算符對對象實例的拷貝是一種淺拷貝,基礎數據會複製一份,但是引用數據拷貝的是它的引用
const obj1 = {a:1, b:2, c:{age: 3}} const obj2 = {...obj1} obj2.a = 2 obj2.c.age = 100 console.log(obj1) // {a: 1, b: 2, c: {age: 100}} console.log(obj2) // {a: 2, b: 2, c: {age: 100}}
展開運算符可以和解構賦值結合起來
const [a, ...b] = [1,2,3,4,5] console.log(a) // 1 console.log(b) // [2, 3, 4, 5]
展開運算符可以把字符串拆成數組
console.log([..."hello"]) // ["h", "e", "l", "l", "o"]
-
剩餘運算符(Rest)
const arr1 = [1,2,3] const [a, ...b] = arr1 console.log(a) // 1 console.log(b) // [2, 3]
const obj1 = {a:1, b:2, c:3} const {a, ...obj2} = obj1 console.log(obj2) // {b: 2, c: 3} console.log(a) // 1
剩餘運算符只能放在最後:
const arr1 = [1,2,3,4,5] const [...b,a] = arr1 // 報錯: Rest element must be last element const [a,...b,c] = arr1 // 報錯: Rest element must be last element
注意:
...
可以叫展開運算符(Spread),也可以叫剩餘運算符(Rest)
具體這個操作符是什麼意思,要看怎麼使用它。
剩餘運算符一般用在函數的參數裏,這樣可以讓函數的參數不受限制。
function fun(item, ...arr) {
console.log(item) // 1
console.log(arr) // [2, 3, 4]
}
fun(1,2,3,4)
持續更新。。。想到啥補點啥