我正在使用 js 对象,可以说:
items: [{text: 'text1', active: true},
{text: 'text1', active: true},
{text: 'text1', active: true}]
我想复制对象并在计算属性中对它们进行一些更改,如下所示:
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
}
}
此代码在控制台中显示:
text from items: something
text from itemsCopy: something
text from items: something
text from itemsCopy: something
text from items: something
text from itemsCopy: something
(?)为什么?我预计:
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
这里出了什么问题?
最佳答案
您没有创建副本。您将对 this.items
的引用分配给 itemsCopy
数组。因此,您稍后会改变同一个数组。
创建副本:
itemsCopy = this.items.slice();
同样的问题也适用于数组中的每个对象。在循环中,创建对象的副本:
var obj = Object.assign({}, itemsCopy[i]);
obj.text = "something";
itemsCopy[i] = obj; //replace the old obj with the new modified one.
<小时/>
演示:
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();
关于javascript - 如何在 javascript/vuejs 中复制对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49028609/