Spreadsegmentfault
以前的rest
只是應用於數組中,ES9
給Object
也新增了rest
和spread
方法。數組
巧了,這兩個方法的符號都是 —— ...
(俗稱三個點)學習
展開操做符spa
將兩個對象合併到一塊兒rest
const input = { a: 1, b: 2 } const output = { c: 3 }
能夠使用...的方式code
const input = { a: 1, b: 2 } const output = { ...input, // 打散到output中,淺拷貝 c: 3 } console.log(input, output) // {a: 1, b: 2} {a: 1, b: 2, c: 3} input.a = 4 console.log(input, output) // 拷貝的形式用的,不是引用,因此原對象沒有進行改變 // {a: 4, b: 2} {a: 1, b: 2, c: 3}
const input = { a: 1, b: 2 } const output = { ...input, a: 3 } console.log(input, output) // {a: 1, b: 2} {a: 3, b: 2} input.a = 4 console.log(input, output) // {a: 4, b: 2} {a: 4, b: 2}
再加一個對象對象
const input = { a: 1, b: 2 } const test = { d: 5 } // 將兩種對象都直接放到目標對象中 const output = { ...input, ...test, c: 3 } console.log(input, output) // {a: 1, b: 2} {a: 1, b: 2, d: 5, c: 3} input.a = 4 console.log(input, output) // {a: 4, b: 2} {a: 1, b: 2, d: 5, c: 3}
以前說過Object.assign()
也能夠合併元素,可是它有一些缺陷,若是不太清楚的能夠看 ES6(六)—— Objectblog
使用spread
會將重複元素替換且由於是合併,因此不會丟失元素,推薦使用rem
const target = { a: { b: { c: 2 } }, e: 5, f: 6, h: 10 } const source = { ...target, a: { b: { c: 3 } }, e: 2, f: 3 } console.log(source) // { a: { b: { c: 3 } }, e: 2, f: 3, h: 10 }
剩餘操做符,這個能夠將對象的剩餘元素和成一個新的對象,原理和spread
正好相反。get
const input = { a: 1, b: 2, c: 3, d: 4, e: 5 } const { a, b, ...rest } = input console.log(a, b, rest) // 1 2 {c: 3, d: 4, e: 5}