js递归实现深拷贝

function getType(data) {
  return Object.prototype.toString.call(data).replace(']', '').substring(8)
}

function _clone(data, res) {
  const type = getType(data)
  if (type === 'Object') {
    Object.keys(data).map(i => {
      if (res[i] === 'Object') {
        res[i] = _clone(data[i], {})
      } else if (res[i] === 'Array') {
        res[i] = _clone(data[i], [])
      } else {
        res[i] = data[i]
      }
    })
  } else if (type === 'Array') {
    data.map(i => {
      const type2 = getType(i)
      if (type2 === 'Object') {
        res.push(_clone(i, {}))
      } else if (type2 === 'Array') {
        res.push(_clone(i, []))
      } else {
        res.push(i)
      }
    })
  } else {
    res = data
  }
  return res
}

function clone(data) {
  const type = getType(data)
  if (type === 'Array') {
    return _clone(data, []) 
  } else if (type === 'Object') {
    return _clone(data, {})
  } else {
    return data
  }
}

const test = {
  name: '张三', age: 18, login: true, habbies: ['打球', {
    a: 'javascript', b: ['vue', {
      [1]: 'react',
      [2]: 'angule'
    }]
  }]
}
const result1 = clone(test)
result1.name = '李四'
result1.habbies = '没有兴趣爱好'

console.log(test, result1)

 

posted @ 2024-04-23 11:33  深海里的星星i  阅读(103)  评论(0)    收藏  举报