js实现深拷贝
js的数据类型分为基本数据类型和引用数据类型。基本数据类型是直接赋值,引用数据类型分为浅拷贝和深拷贝。浅拷贝是复制对象的指针,深拷贝是复制对象所有属性再内存中独立存在。
浅拷贝如下:
var obj = {a: 'test', b: {c: 0}} var obj1 = obj var obj2 = shallowCopy(obj); function shallowCopy(src) { var dst = {}; for (var prop in src) { if (src.hasOwnProperty(prop)) { dst[prop] = src[prop]; } } return dst; } var obj3 = Object.assign({}, obj) obj.a = 'arr' obj.b.c = 1 console.log(obj) // {a: 'arr', b: {c: 1}} console.log(obj1) // {a: 'arr', b: {c: 1}} console.log(obj2) // {a: 'test', b: {c: 1}} console.log(obj3) // {a: 'test', b: {c: 1}}
深拷贝实现如下:
function extend (source) { var target if (typeof source === 'object') { target = Array.isArray(source) ? [] : {} for (var key in source) { if (source.hasOwnProperty(key)) { if (typeof source[key] !== 'object') { target[key] = source[key] } else { target[key] = extend(source[key]) } } } } else { target = source } return target } var obj1 = {a: {b: 0}} var cpObj1 = extend(obj1) obj1.a.b = 1 console.log(cpObj1) // {a: {b: 0}} var obj2 = [[0]] var cpObj2 = extend(obj2) obj2[0][0] = 1 console.log(cpObj2) // [[0]]