美文网首页
手写深拷贝

手写深拷贝

作者: 宏_4491 | 来源:发表于2021-03-31 16:49 被阅读0次
    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
        }
    

    相关文章

      网友评论

          本文标题:手写深拷贝

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