如何通过“按值传递”复制元素不是通过“通过引用传递”;
下面是代码片段。基本上,“this.leaves”是一个数组。我想移动第一个数组元素,复制它(称为 frontLeaf),然后将其取消移动到原始数组,更改复制元素的一些属性,然后将该元素放入父数组元素。
var frontLeaf = this.leaves.shift();
this.leaves.unshift(frontLeaf);
frontLeaf.leftChild = tmp;
frontLeaf.rightChild = this;
this.parent.leaves.push(frontLeaf);
我的问题是 frontLeaf 似乎是通过引用传递的,当我分配
frontLeaf.leftChild = tmp;
frontLeaf.rightChild = this;
上面两行代码时似乎会影响 this.leaves 和 this.parent.leaves 中的两个元素...那么,我该如何解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Javascript 通过引用传递所有对象。完成您想要的操作的唯一方法是创建一个全新的对象,进行深度复制,然后推送它。
有关使用 jQuery 的示例解决方案,请参阅这篇文章。
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.
是的,在 JavaScript 中对象总是通过引用传递。如果您想要一个对象的副本,您必须自己编写一个深复制例程。
我不确定你到底想做什么(tmp 是什么?这是什么?this.leaves 数组是什么?),但也许有一种方法可以做到而不需要副本?
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?
这是我在遇到同样问题时所做的:
Here's what I did when faced the same issue: