其他分享
首页 > 其他分享> > 兼容ie8的多维数组——深拷贝

兼容ie8的多维数组——深拷贝

作者:互联网

浅拷贝只是把对象的内存位置指针给拷贝了,若修改拷贝对象,则原对象也会跟踪修改。

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))

  

 

标签:ie8,rows,object,50,兼容,var,orgid,多维,cols
来源: https://www.cnblogs.com/hpx2020/p/10967970.html