對象的擴展運算符(...),用於取出參數對象中的所有可遍歷屬性,然後拷貝到當前對象之中 對象擴展運算符: 1. 複製對象 let obj1 = { x: 1, y: 2, z: 3 } let obj2 = { ...obj1 } obj2 = { x: 1, y: 2, z: 3 } 2. 合併對 ...
對象的擴展運算符(...),用於取出參數對象中的所有可遍歷屬性,然後拷貝到當前對象之中
對象擴展運算符:
1. 複製對象
let obj1 = { x: 1, y: 2, z: 3 }
let obj2 = { ...obj1 }
obj2 = { x: 1, y: 2, z: 3 }
2. 合併對象
let obj1 = { x: 1, y: 2, z: 3 }
let obj2 = { x: 4, y: 5, z: 6 }
let obj3 = { ...obj1, ...obj2 }
obj3 = { x: 1, y: 2, z: 3, x: 4, y: 5, z: 6 }
3. 自定義屬性
let obj1 = { x: 1, y: 2, z: 3 }
let obj2 = { ...obj1, a: 4, b: 5, c: 6 }
obj2 = { x: 1, y: 2, z: 3, a: 4, b: 5, c: 6 }
註意:若自定義屬性在擴展運算符的後面,且與擴展運算符內的屬性同名,則擴展運算符內的屬性會被覆蓋掉
數組擴展運算符
1. 複製數組
let arr1 = [1, 2, 3]
let arr2 = [ ...arr1 ]
arr2 = [1, 2, 3]
2. 合併數組
let arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let arr3 = [ ...arr1, ...arr2 ]
arr3 = [1, 2, 3, 4, 5, 6]
3. 字元串變數組
let arr1 = [1, 2, 3]
let str1 = 'hello'
let arr2 = [...arr1, ...str1]
arr2 = [ 1, 2, 3, "h", "e", "l", "l", "o" ]