定义
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param sources One or more source objects from which to copy properties
*/
assign(target: object, ...sources: any[]): any;
可以看出:
Object.assign()
方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象,并且返回目标对象Object.assign()
第一个参数是目标对象,第二个参数使用...sources
表明允许传递多个源对象
举个栗子
const target = { a: 1, b: 2 };
const source = { b: 3, c: 4 };
const res = Object.assign(target, source);
// 输出Object { a: 1, b: 3, c: 4 }
console.log(target);
// 输出 Object { a: 1, b: 3, c: 4 }
console.log(res);
即源对象source参数会添加到目标对象target中,如果key相同则会覆盖目标对象数据
happy coding!