英文:
Issue with copy array in JavaScript
问题
我使用[...array]
复制了我的数组,然后尝试修改其中的某些内容,但我不想修改原始表格,但它也修改了我的数组,我不明白为什么。
var users = [{ userUID: '123', userName: 'TOTO' }, { userUID: '345', userName: 'TITI' }, { userUID: '678', userName: 'TATA' }];
var list = [...users];
var listModified = list.map(x => x.userName = x.userUID === '678' ? '' : x.userName);
console.log(users);
所以我想要做的是复制表格,获取数据并修改特定数据,但不要修改我的用户列表。
英文:
I copy my array with [...array]
and try to modify something inside but i don't want to modify the original table but it modify my array also and I don't understand why
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var users = [{userUID : '123', userName : 'TOTO'},{userUID : '345', userName : 'TITI'},{userUID : '678', userName : 'TATA'}]
var list = [...users]
var listModifie = list.map(x => x.userName = x.userUID == '678' ? '' : x.userName)
console.log(users)
<!-- end snippet -->
So what I want to do is copy the table get the data modify a specific data but not modify my users list
答案1
得分: 0
你正在经历的行为是由JavaScript处理对象和数组的方式引起的。扩展运算符[...array]创建原始数组的浅拷贝,但它只复制数组中对象的引用,而不是对象本身。因此,新数组和原始数组仍然指向内存中的相同对象。
在你的代码中,当你使用list.map()修改对象的userName属性时,它会影响原始的users数组和list数组,因为它们都引用相同的对象。
实现这一目标的一种方法是使用JSON.parse()和JSON.stringify()对数组进行序列化和反序列化:
var list = JSON.parse(JSON.stringify(users));
var listModified = list.map(x => x.userUID === 'azeaz-azeze-azeaze' ? { ...x, userName: '' } : x);
另一种选择是在map()中使用扩展运算符:
var list = users.map(obj => ({ ...obj }));
var listModified = list.map(x => x.userUID === 'azeaz-azeze-azeaze' ? { ...x, userName: '' } : x);
英文:
The behavior you are experiencing is due to how JavaScript handles objects and arrays. The spread operator [...array] creates a shallow copy of the original array, but it only copies the references to the objects within the array, not the objects themselves. As a result, the new array and the original array still point to the same objects in memory.
In your code, when you modify the userName property of the objects using list.map(), it affects both the original users array and the list array because they are both referencing the same objects.
One way to achieve this is by using JSON.parse() and JSON.stringify() to serialize and deserialize the array:
var list = JSON.parse(JSON.stringify(users));
var listModified = list.map(x => x.userUID === 'azeaz-azeze-azeaze' ? { ...x, userName: '' } : x);
Another option is to use spread operator with map()::
var list = users.map(obj => ({ ...obj }));
var listModified = list.map(x => x.userUID === 'azeaz-azeze-azeaze' ? { ...x, userName: '' } : x);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论