浅拷贝只是把对象的内存位置指针给拷贝了,若修改拷贝对象,则原对象也会跟踪修改。
var a = {a : 'old', b : { c : 'old'}}
var b = Object.assign({}, a)
b.a = 'new'
b.b.c = 'new'
console.log(a) // { a: 'old', b: { c: 'new' } }
console.log(b) // { a: 'new', b: { c: 'new' } } 改变b的时候a也跟着发生变化
以下是兼容ie8以下的多维数组深拷贝
function deepCopy(p, c) { c = c || {}; for (var i in p) { if (p.hasOwnProperty(i)) { if (typeof p[i] === 'object') { c[i] = (p[i] instanceof Array) ? [] : {}; deepCopy(p[i], c[i]); } else { c[i] = p[i]; } } } return c; } var CardViewData = [{rows: [40, 60], cols: [100], items: [ {rows: [100], cols: [30, 40, 30], items: [ {orgid: 1, object: {}}, {orgid: 2, object: {}}, {orgid: 3, object: {}} ]}, {rows: [100], cols: [50, 50], items: [ {rows: [50, 50], cols: [50, 50], items: [ {orgid: 4, object: {}}, {orgid: 5, object: {}}, {colspan: 2, orgid: 6, object: {}} ]}, {rows: [50, 50], cols: [100], items: [ {orgid: 7, object: {}}, {orgid: 8, object: {}} ]} ]}, ]}]; var mydeep = deepCopy(CardViewData) console.log(JSON.stringify(mydeep))
另一种深拷贝方法
function deepClone(obj) { // 如果是 值类型 或 null,则直接return if(typeof obj !== 'object' || obj === null) { return obj } // 定义结果对象 let copy = {} // 如果对象是数组,则定义结果数组 if(obj.constructor === Array) { copy = [] } // 遍历对象的key for(let key in obj) { // 如果key是对象的自有属性 if(obj.hasOwnProperty(key)) { // 递归调用深拷贝方法 copy[key] = deepClone(obj[key]) } } return copy }