js代码积累:js对象复制

xiaoxiao2021-02-28  96

对象复制

在写vue相关代码时,有时把同一个对象或者数组赋值给不同的变量,如果修改其中一个值,另外一个变量的值也会变化,如下:

let orderDetailList = this.order.orderDetailList; if (orderDetailList != undefined && typeof(orderDetailList) != undefined && orderDetailList != '') { for (let i in orderDetailList) { this.productTable.push(orderDetailList[i]); } }

因为某些需求,我修改了this.productTable的值,结果this.order.orderDetailList中的内容也发生了变化。原因很简单,两个数组中的对象是相同内容的引用。 为了解决这个问题,想到了一种方法,把this.order.orderDetailList中对象的内容全部复制到新的对象上,这样既能把值传过去,修改也不会影响原来的值,但是js对象复制代码没有写出来,从网上找了一篇博客,解决了我的问题,代码如下:

//深复制对象方法 cloneObj(obj) { var newObj = {}; if (obj instanceof Array) { newObj = []; } for (var key in obj) { var val = obj[key]; newObj[key] = typeof val === 'object' ? this.cloneObj(val): val; } return newObj; },

赋值代码改成下面样子:

let orderDetailList = this.order.orderDetailList; if (orderDetailList != undefined && typeof(orderDetailList) != undefined && orderDetailList != '') { for (let i in orderDetailList) { let asd = this.cloneObj(orderDetailList[i]); this.productTable.push(asd); } }

这样问题就解决了。

复制代码来自博客

转载请注明原文地址: https://www.6miu.com/read-38899.html

最新回复(0)