Object.assign()

123 阅读1分钟

Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象分配到目标对象。它将返回目标对象。

语法:

Object.assign(target, ...sources)

如果目标对象中的属性具有相同的键,则属性将被源对象中的属性覆盖。后面的源对象的属性将类似地覆盖前面的源对象的属性。

let target = {name: 'aa', age: 20}
let source = {sex: 'male', age: 30}
let result = Object.assign(target, source)
console.log(JSON.stringify(result))  // {"name":"aa","age":30,"sex":"male"}
let target = {name: 'aa', age: 20}
let s1 = {sex: 'male', age: 30}
let s2 = {sex: 'female', skill: 'say'}
let result = Object.assign(target, s1, s2)
console.log(JSON.stringify(result)) // {"name":"aa","age":30,"sex":"female","skill":"say"}

Object.assign() 是浅拷贝,拷贝的是(可枚举)属性值,假如源值是一个对象的引用,它仅仅会复制其引用值

let source = {name: 'js', hobby: ['a', 'b', 'c']}
let target = Object.assign({}, source)
console.log(JSON.stringify(target)) // {"name":"js","hobby":["a","b","c"]}
​
target.name = 'css'
console.log(JSON.stringify(target)) // {"name":"css","hobby":["a","b","c"]}
console.log(JSON.stringify(source)) // {"name":"js","hobby":["a","b","c"]}
​
target.hobby[0] = '1'
console.log(JSON.stringify(target)) // {"name":"css","hobby":["1","b","c"]}
console.log(JSON.stringify(source)) // {"name":"js","hobby":["1","b","c"]}

developer.mozilla.org/zh-CN/docs/…