对象a,b代码如下:
let a = {
nickname: "Attention",
age: 23
}
let b = {
gender: 1,
}
方法一:改变原对象数据,使用ES6剩余函数参数来进行操作
let a = {
nickname: "Attention",
age: 23
}
let b = {
gender: 1,
...a
}
console.log(b);
此时打印对象b为:
方法二:不改变原对象数据时,使用函数extend来进行操作,使用for in遍历
let a = {
nickname: "Attention",
age: 23
}
let b = {
gender: 1,
}
function extend(target, source) {
for (const key in source) {
target[key] = source[key]
}
}
extend(b, a)
console.log(b);
此时打印对象b为:
方法三:不改变原对象数据时,使用函数extend来进行操作,使用ES6 + forEach遍历
let a = {
nickname: "Attention",
age: 23
}
let b = {
gender: 1,
}
function extend(target, source) {
Object.keys(source).forEach(key => {
target[key] = source[key]
})
}
extend(b, a)
console.log(b);
此时打印对象b为: