一点一滴学前端 - Object.assign()

一. 简介

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

简单总结如下两点:

  • 如果对象存在,将覆盖对象
  • 如果对象不存在,将新增对象

二. 语法格式

Object.assign(target, ...sources)

可以将多个对象合并到目标对象!!!

三. 示例

单参数示例

const target = { name: "张三", age: 20 };
const source = { name: "李四", school: "清华大学"};

const result = Object.assign(target, source);

console.log("source == ", source);
console.log("target == ", target);
console.log("result == ", result);

运行日志

source ==  {name: "李四", school: "清华大学"}
target ==  {name: "李四", age: 20, school: "清华大学"}
result ==  {name: "李四", age: 20, school: "清华大学"}

多参数示例

const target = { name: "张三", age: 20 };
const source = { name: "李四", school: "清华大学"};
const source2 = { age: 30, hobby: "篮球"};

const result = Object.assign(target, source, source2);

console.log("target == ", target);
console.log("result == ", result);

运行日志

target ==  {name: "李四", age: 30, school: "清华大学", hobby: "篮球"}
result ==  {name: "李四", age: 30, school: "清华大学", hobby: "篮球"}

你可能感兴趣的:(前端)