深拷贝

作者: BingeryLamb | 来源:发表于2020-01-16 17:37 被阅读0次
    function deepClone (o) {
        if(typeof o !== 'object') return o
        let n
        if(Array.isArray(o)){
            n = new Array(o.length)
            o.forEach((v,i)=>{n[i] = deepClone(v)})
        } else {
            n = {}
            Object.keys(o).forEach((key)=>{n[key] = deepClone(o[key])})
        }
        return n
    }
    

    测试

    const a = {
      a: [
        1,
        [4],
        {
          a: {
            c: [4]
          }
        }
      ]
    }
    
    const b = deepClone(a);
    
    a.c = "c";
    console.log(a);
    console.log(b);
    console.log(a.c);
    console.log(b.c);
    

    相关文章

      网友评论

          本文标题:深拷贝

          本文链接:https://www.haomeiwen.com/subject/zqxqzctx.html