猿问

vue中 实现对象的深拷贝

自己定义了一个对象,因该对象要做双向数据绑定操作,因开发需要所以要备份一下该对象的初始状态,但是普通的备份对象无效仍然会因双向数据绑定而导致备份对象跟着改变,请教如何用深拷贝备份初始对象。

慕森王
浏览 1783回答 4
4回答

12345678_0001

function deepClone(data){&nbsp; &nbsp; &nbsp; &nbsp;var type = getType(data);&nbsp; &nbsp; &nbsp; &nbsp;var obj;&nbsp; &nbsp; &nbsp; &nbsp;if(type === 'array'){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;obj = [];&nbsp; &nbsp; &nbsp; &nbsp;} else if(type === 'object'){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;obj = {};&nbsp; &nbsp; &nbsp; &nbsp;} else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//不再具有下一层次&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return data;&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;if(type === 'array'){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for(var i = 0, len = data.length; i < len; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;obj.push(deepClone(data[i]));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;} else if(type === 'object'){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for(var key in data){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;obj[key] = deepClone(data[key]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;return obj;&nbsp; &nbsp;}

墨色风雨

一般用 JSON.parse(JSON.stringify(data)) 就可以了。如果你要使用这种方式,有几个&nbsp;注意事项&nbsp;需要了解下

慕沐林林

可以用lodash的cloneDeep函数。狠一点就上immutable,facebook官方出的,所有数据都是不可变,不需要深拷贝之类的操作

浮云间

纯数据对象的话可以用JSON的接口,var&nbsp;obj_snapshot&nbsp;=&nbsp;JSON.parse(JSON.stringify(obj))如果是带有function的js对象的话,那就。。。复杂点,写个克隆吧
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答