關於ES6的對象擴展運算符


對象的擴展運算符(...),用於取出參數對象中的所有可遍歷屬性,然后拷貝到當前對象之中

 

對象擴展運算符

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" ]


免責聲明!

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



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