【问题标题】:how to make a copy of object in javascript/vuejs [duplicate]如何在javascript / vuejs中制作对象的副本[重复]
【发布时间】:2018-08-08 06:38:34
【问题描述】:

我正在使用 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

这里有什么问题?

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    您不是在创建副本。您将对 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();

    【讨论】:

    • 哦,我明白了...但是使用 this.items.slice(); 给了我相同的结果...
    • @gileneusz,对不起。忘记了你的数组有对象。请参阅上面的更新。
    • 你确定你没有忘记什么吗?您是否同时执行了 slice() 和 Object.assign()?
    • 哦,我想念 slice(),现在它可以工作了。唯一的区别是在 vue 中我将 itemsCopy = items.slice(); 更改为 'this.items.slice();'。感谢您的帮助!
    • 非常感谢@Chris 你救了我的命:D
    猜你喜欢
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    相关资源
    最近更新 更多