手写深拷贝

2021-03-31  本文已影响0人  宏_4491
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
 // const targetObj = Array.isAarray=== Array ? [] : {}
// const targetObj = obj instanceof Array ? [] :{}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

    function deepClone(obj) {
        if (typeof obj !== "object" || obj === null) {
            return obj
        }
        //判断是数组还是对象
        let result = obj instanceof Array ? [] : {};
        for (let key in obj) {
            if(obj.hasOwnProperty(key)){
                result[key] = deepClone(obj[key])
            }
        }
        return result
    }
上一篇 下一篇

猜你喜欢

热点阅读