如何在 javascript/vuejs 中制作对象的副本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49028609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to make a copy of object in javascript/vuejs
提问by gileneusz
I'm working with js object, lets say:
我正在使用 js 对象,可以说:
items: [{text: 'text1', active: true},
{text: 'text1', active: true},
{text: 'text1', active: true}]
I want to make the copy of the object and make some changes with them in computed property like this way:
我想制作对象的副本并在计算属性中对它们进行一些更改,如下所示:
computed: {
copyAndChange() {
var itemsCopy = []
itemsCopy = this.items
for (var i=0; i<itemsCopy.length; i++) {
itemsCopy[i].text = "something"
console.log('text from items: ' + this.item[i])
console.log('text from itemsCopy: ' + itemsCopy[i])
}
return itemsCopy
}
}
This code gives me in console:
这段代码在控制台中给了我:
text from items: something
text from itemsCopy: something
text from items: something
text from itemsCopy: something
text from items: something
text from itemsCopy: something
(?) why? I expected:
(?) 为什么?我期望:
This code gives me in console:
text from items: text1
text from itemsCopy: something
text from items: text1
text from itemsCopy: something
text from items: text1
text from itemsCopy: something
what is wrong here?
这里有什么问题?
回答by Chris
You are not creating a copy. You are assigning the reference to this.itemsto your itemsCopyarray. Thus, you are later mutating the same array.
您不是在创建副本。您正在将引用分配this.items给您的itemsCopy数组。因此,您稍后将改变相同的数组。
Create a copy with:
创建一个副本:
itemsCopy = this.items.slice();
The same issue applies with each object inside your array. In your loop, create a copy of the object:
同样的问题适用于数组中的每个对象。在您的循环中,创建对象的副本:
var obj = Object.assign({}, itemsCopy[i]);
obj.text = "something";
itemsCopy[i] = obj; //replace the old obj with the new modified one.
Demo:
演示:
var items = [
{text: 'text1', active: true},
{text: 'text1', active: true},
{text: 'text1', active: true}
];
function copyAndChange() {
var itemsCopy = []
itemsCopy = items.slice();
for (var i=0; i<itemsCopy.length; i++) {
var obj = Object.assign({}, itemsCopy[i]);
obj.text = "something";
itemsCopy[i] = obj; //replace the old obj with the new modified one.
console.log('text from items: ' + items[i].text)
console.log('text from itemsCopy: ' + itemsCopy[i].text)
}
return itemsCopy
}
copyAndChange();

