更改和分配没有副作用的对象

编程入门 行业动态 更新时间:2024-10-21 03:22:00
本文介绍了更改和分配没有副作用的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前有以下代码:

var myArray = []; var myElement = { id: 0, value: 0 } myElement.id = 0; myElement.value = 1; myArray[0] = myElement; myElement.id = 2; myElement.value = 3; myArray[1] = myElement;

问题是当我更改 id 和 value ,值也会在第一个元素中更改。有没有一种方法可以继续添加新元素而不更改数组中先前插入的值的值?

The problem is that when I change the value of id and value for my second element, the values also change in the first element. Is there a way that I can keep adding new elements without it changing the value of the previously inserted values in the array?

推荐答案

请改为尝试:

var myArray = []; myArray.push({ id: 0, value: 1 }); myArray.push({ id: 2, value: 3 });

或这不适用于您的情况?

or will this not work for your situation?

更多推荐

更改和分配没有副作用的对象

本文发布于:2023-11-14 00:36:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585736.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:副作用   分配   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!