深拷贝和浅拷贝

//浅拷贝
function shallowClone(data) {
  var cloneData ={}
  for(var i in data) {
    if(data.hasOwnProperty(i)) {
      cloneData[i] = data[i]
    }
  }
  return cloneData
}

//深拷贝 浅拷贝+递归
function deepClone(data){
  var cloneData ={}
  for(var i in data) {
    if(data.hasOwnProperty(i)){
      if(typeof data[i] == 'object') {   //Object.prototype.toString.call(data[i]) == '[Object Object]'
        cloneData[i] = deepClone(data[i])  //递归
      } else {
        cloneData[i] = data[i]
      }
    }
  }
  return cloneData
}

//指定深度和广度
function createData(deep, breadth) {
  var data = {}
  var temp = data
  for(var i=0;i<deep;i++){
    temp = temp['data'] = {}
    for(var j=0;j<breadth;j++) {
      temp[j] = j
    }
  }
  return data
}

createData(1, 3); // 1层深度,每层有3个数据 {data: {0: 0, 1: 1, 2: 2}}
createData(3, 0); // 3层深度,每层有0个数据 {data: {data: {data: {}}}}

JSON.parse(JSON.stringify(data))

//破解递归爆栈
function cloneLoop(x){
  const root = {}
  const loopList = [{
    parent: root,
    key: undefined,
    data: x
  }]
  while(loopList.length) {
    //深度优先
    const node = loopList.pop()
    const parent = node.parent;
    const key = node.key;
    const data = node.data;
    // 初始化赋值目标,key为undefined则拷贝到父元素,否则拷贝到子元素
    let res = parent;
    if(typeof key !== 'undefined'){
      res = parent[key] = {}
    }
    for(var i in data) {
      if(typeof data[i] === 'object'){
        loopList.push({
          parent: res,
          key: i,
          data: data[i]
        })
      }else{
        res[i] = data[i]
      }
    }
  }
  return root
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值