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.n2andnewObj.n2are the same?And as in my previous comment, when I copy:
Another question, when I create an object by
Object.createlike 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.assignis 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.assignreturns the target object, we are able to store the resulting assigned object into thecloneFoodvariable. We could switch our example up and use the following:Obviously the value of
beefin ourfoodobject is wrong, so we can assign the correct value ofbeefusingObject.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
foodwhich 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
foodwithletorvarwhich 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...