how to make a copy of object in javascript/vuejs
本问题已经有最佳答案,请猛点这里访问。
我使用的是JS对象,比如:
1 2 3 | items: [{text: 'text1', active: true}, {text: 'text1', active: true}, {text: 'text1', active: true}] |
我想复制对象并在计算属性中对其进行一些更改,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 | 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 } } |
这个代码在控制台中给出了我:
1 2 3 4 5 6 | text from items: something text from itemsCopy: something text from items: something text from itemsCopy: something text from items: something text from itemsCopy: something |
(?)为什么?我料想:
1 2 3 4 5 6 7 | 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 |
这里怎么了?
您没有创建副本。您正在将对
创建副本时使用:
1 | itemsCopy = this.items.slice(); |
同样的问题也适用于数组中的每个对象。在循环中,创建对象的副本:
1 2 3 | var obj = Object.assign({}, itemsCopy[i]); obj.text ="something"; itemsCopy[i] = obj; //replace the old obj with the new modified one. |
演示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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(); |