Object.assign()
时间: 2023-10-28 17:51:33 浏览: 31
Object.assign() is a method in JavaScript that is used to merge two or more objects into a single object. The method takes two or more objects as arguments, and merges the properties and values of all objects into a new, single object. The method is commonly used in JavaScript programming for a variety of tasks, such as creating a new object with the properties of multiple objects, or updating an existing object with new properties or values. The method is also useful for copying the properties and values of one object to another object.
相关问题
Object.assign
`Object.assign()`是JavaScript中的一个静态方法,用于将一个或多个源对象的属性(source object)复制到目标对象(target object)。它接受任意数量的参数,其中第一个参数是要复制到的目标对象,后续参数是源对象,按照它们在参数列表中出现的顺序进行复制。如果多个源对象具有相同的属性,则后面的对象会覆盖前面的对象。
`Object.assign()`方法的语法如下:
```
Object.assign(target, ...sources)
```
其中:
- `target`:目标对象,将从源对象复制属性到该对象。
- `sources`:源对象数组,包含一个或多个源对象,将从这些对象复制属性到目标对象。
`Object.assign()`方法返回目标对象,即被复制后的目标对象。
以下是一个简单的示例,演示了如何使用`Object.assign()`方法将两个对象合并:
```
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const result = Object.assign(target, source);
console.log(target); // { a: 1, b: 4, c: 5 }
console.log(result); // { a: 1, b: 4, c: 5 }
```
在这个例子中,我们定义了两个对象`target`和`source`,然后使用`Object.assign()`方法将`source`对象的属性复制到`target`对象中。由于`source`对象具有与`target`对象相同的属性`b`,因此`b: 2`被`b: 4`覆盖。最后,`Object.assign()`方法返回合并后的目标对象,也就是`{ a: 1, b: 4, c: 5 }`。
object.assign
`Object.assign()` 是一个静态方法,用于将一个或多个源对象的可枚举属性复制到目标对象中。它会返回目标对象。
`Object.assign(target, ...sources)`
- `target`:目标对象,即将属性复制到的对象。
- `sources`:源对象,一个或多个对象,从中复制属性。
示例代码:
```javascript
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const result = Object.assign(target, source);
console.log(target); // 输出 { a: 1, b: 4, c: 5 }
console.log(result); // 输出 { a: 1, b: 4, c: 5 }
```
在上面的例子中,`Object.assign()` 将 `source` 对象的属性复制到 `target` 对象中,如果属性名相同,则后面的属性值会覆盖前面的属性值。最后,`Object.assign()` 返回的是目标对象 `target`。