数组合并
//es5
let book1 = ['平凡的世界第一部', '平凡的世界第二部', '平凡的世界第三部']
let book2 = ['人生']
let book3 = book1.concat(book2);
//console.log(book3) // (4) ["平凡的世界第一部", "平凡的世界第二部", "平凡的世界第三部", "人生"]
//es6
let book4 = [...book1, ...book2];
book4[3] = '月夜静悄悄'
console.log(book4) //(4) ["平凡的世界第一部", "平凡的世界第二部", "平凡的世界第三部", "月夜静悄悄"]
对象合并
let obj1 = {
book1: '平凡的世界第一部',
book2: '平凡的世界第二部',
book3:'平凡的世界第三部',
}
let obj2 = {
...obj1,
book4:'人生',
}
console.log(obj2) //{book1: "平凡的世界第一部", book2: "平凡的世界第二部", book3: "平凡的世界第三部", book4: "人生"}
//如后者与前者相同,后者覆盖前者
let obj1 = {
book1: '平凡的世界第一部',
book2: '平凡的世界第二部',
book3: '平凡的世界第三部',
book4: '月夜静悄悄',
}
let obj2 = {
...obj1,
book4: '月夜静悄悄11111',
book5: '人生',
}
console.log(obj2) //{book1: "平凡的世界第一部", book2: "平凡的世界第二部", book3: "平凡的世界第三部", book4: "月夜静悄悄11111", book5: "人生"}
let obj = { name: 'daisy', }
let obj1 = { job: 'web', }
let obj2 = { sex: 1, }
let obj5 = { ...obj, ...obj1, ...obj2 }
console.log(obj5) //{name: "daisy", job: "web", sex: 1}
//与Object.assign用法相同 Object.assign(target, ...sources)
let obj4 = Object.assign(obj, obj1, obj2);
console.log(obj4) //{name: "daisy", job: "web", sex: 1}
console.log(obj) //{name: "daisy", job: "web", sex: 1} /**注意目标对象也会随之改变 */
Object.assign的详细用法参考资料:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign