Because objects in #JavaScript are references values, you can't simply just copy using the =. But no worries, here are 3 ways for you to clone an...
For further actions, you may consider blocking this person and/or reporting abuse
Also have some issues when clone object with
JSON.parse(JSON.stringify)
Can you check?
I should of mentioned...the JSON method wonβt be able to clone methods π£
Check out this article, it has more info:
google.ca/amp/s/scotch.io/bar-talk...
Thank you,
And I have some questions about this,
When I copy:
obj.n2
andnewObj.n2
are the same?And as in my previous comment, when I copy:
Another question, when I create an object by
Object.create
like this:Why that, we cannot clone it without readable it? Please help me understand, thank you!
What is difference between spread and object.assign?
I'ts important to note that
Object.assign
is a function which modifies and returns the target object. In Samantha's example using the following,{}
is the object that is modified. The target object is not referenced by any variable at that point, but becauseObject.assign
returns the target object, we are able to store the resulting assigned object into thecloneFood
variable. We could switch our example up and use the following:Obviously the value of
beef
in ourfood
object is wrong, so we can assign the correct value ofbeef
usingObject.assign
. We aren't actually using the returned value of the function at all, but we are modifying our target object which we have referenced with the constfood
.Spread on the other hand is an operator which copies properties of one object into a new object. If we wanted to replicate the above example using spread to modify our variable
food
......we get an error, because we use spread when creating new objects, and therefore are assigning a whole new object to
food
which was declared withconst
, which is illegal. So we can either choose to declare a new variable to hold our new object in, like the following:or we could declare
food
withlet
orvar
which would allow us to assign a whole new object:Got it. Thank you!
Thanks for chiming in and helping answer this question. This is great, let me add it to the code notes π
Thu explanation is swift. Thanks
I don't think there is a difference aside from syntax in this case. The triple dot expression
...
also means rest which does not meanObject.assign
.For more information see 2ality.com/2016/10/rest-spread-pro...