如何通过“按值传递”复制元素不是通过“通过引用传递”;

发布于 2024-11-01 19:39:57 字数 496 浏览 2 评论 0原文

下面是代码片段。基本上,“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

埋情葬爱 2024-11-08 19:39:57

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.

把人绕傻吧 2024-11-08 19:39:57

是的,在 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?

哭了丶谁疼 2024-11-08 19:39:57

这是我在遇到同样问题时所做的:

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

Here's what I did when faced the same issue:

var newObj = JSON.parse(JSON.stringify(oldObj));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文