简体   繁体   中英

How can I copy element by 'pass by value' not by 'pass by reference'

Below is the snippet of the code. Basically, 'this.leaves' is a array. And I want to shift first array element, make copy of it (called frontLeaf), and unshift it to the original array, change some attributes from copied element, and put that element to the parent array element.

var frontLeaf = this.leaves.shift();
this.leaves.unshift(frontLeaf);
frontLeaf.leftChild = tmp;
frontLeaf.rightChild = this;
this.parent.leaves.push(frontLeaf);

My problem is that frontLeaf seems to be passed by reference that when I assign

frontLeaf.leftChild = tmp; 
frontLeaf.rightChild = this;

above two lines of code seems to affect both elements in this.leaves and this.parent.leaves... So, How can I resolve this problem?

这是我遇到相同问题时所做的事情:

var newObj = JSON.parse(JSON.stringify(oldObj));

Yes, in JavaScript objects are always passed by reference. If you want a copy of an object, you'll have to write a deep-copy routine yourself.

I'm not sure exactly what you're trying to do (what is tmp? what is this? what is this.leaves an array of?), but maybe there is a way to do it without needing a copy?

Javascript passes all objects by reference. The only way to do what you're looking for is to create an entirely new object, do a deep copy and then push it.

See this post for a sample solution using jQuery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM