assign复制对象_对象的assign()方法

assign复制对象

Introduced in ES2015, this method copies all the enumerable own properties of one or more objects into another.

此方法在ES2015ES2015 ,将一个或多个对象的所有可枚举的自身属性复制到另一个对象中。

Its primary use case is to create a shallow copy of an object.

它的主要用例是创建对象的浅表副本。

const copied = Object.assign({}, original)

Being a shallow copy, values are cloned, and objects references are copied (not the objects themselves), so if you edit an object property in the original object, that’s modified also in the copied object, since the referenced inner object is the same:

作为浅表副本,将克隆值并复制对象引用(而不是对象本身),因此,如果在原始对象中编辑对象属性,则在复制的对象中也将对其进行修改,因为引用的内部对象是相同的:

const original = {
  name: 'Fiesta',
  car: {
    color: 'blue'
  }
}
const copied = Object.assign({}, original)

original.name = 'Focus'
original.car.color = 'yellow'

copied.name //Fiesta
copied.car.color //yellow

I mentioned “one or more”:

我提到“一个或多个”:

const wisePerson = {
  isWise: true
}
const foolishPerson = {
  isFoolish: true
}
const wiseAndFoolishPerson = Object.assign({}, wisePerson, foolishPerson)

console.log(wiseAndFoolishPerson) //{ isWise: true, isFoolish: true }

翻译自: https://flaviocopes.com/javascript-object-assign/

assign复制对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值