javascript - 如何在 javascript/vuejs 中复制对象

标签 javascript vue.js

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

相关文章:

javascript - 正则表达式替换不会评估现有变量,返回未定义

javascript - 在窗口上添加 Vue.js 事件

vue.js - 无法获取数组的索引

vue.js - Vuetify 数据表 - 扩展项目插槽转换

javascript - 使用 VBA 显示 javascript 警报

javascript - 更改数组中所有元素的属性值,但只需要一个

javascript - 单击时父元素的 AngularUI 弹出框样式发生变化

Vue.js/Mixins - 有没有办法在 vue 组件之外获取全局 mixin 对象?

javascript - Vuetify 在焦点上打开选择/自动完成/组合框菜单

javascript - 使用选项卡时调整图表高度大小