如何在javascript/vuejs中复制对象
我正在使用js对象,假设:如何在javascript/vuejs中复制对象,javascript,vue.js,Javascript,Vue.js,我正在使用js对象,假设: items: [{text: 'text1', active: true}, {text: 'text1', active: true}, {text: 'text1', active: true}] 我想复制对象,并在computed属性中对其进行一些更改,如下所示: computed: { copyAndChange() { var itemsCopy = [] itemsCopy = this.items for (v
items: [{text: 'text1', active: true},
{text: 'text1', active: true},
{text: 'text1', active: true}]
我想复制对象,并在computed属性中对其进行一些更改,如下所示:
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: 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项目=[
{text:'text1',active:true},
{text:'text1',active:true},
{text:'text1',active:true}
];
函数copyAndChange(){
var itemsCopy=[]
itemsCopy=items.slice();
对于(var i=0;ioh,我明白了…但是使用this.items.slice();
会得到相同的结果…@gileneusz,对不起。忘记了数组中有对象。请参阅上面的更新。你确定没有忘记什么吗?你同时执行了slice()和Object.assign()?哦,我错过了slice()唯一的区别是,在vue中,我将itemsCopy=items.slice();
更改为“this.items.slice();”。感谢您的帮助!非常感谢@Chris您救了我的命:D
var obj = Object.assign({}, itemsCopy[i]);
obj.text = "something";
itemsCopy[i] = obj; //replace the old obj with the new modified one.