How to Deep clone in javascript

前端 未结 19 1538
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:06

How do you deep clone a JavaScript object?

I know there are various functions based on frameworks like JSON.parse(JSON.stringify(o)) and $.extend(t

19条回答
  •  礼貌的吻别
    2020-11-22 02:45

    This solution will avoid recursion problems when using [...target] or {...target}

    function shallowClone(target) {
      if (typeof a == 'array') return [...target]
      if (typeof a == 'object') return {...target}
      return target
    }
    
    /* set skipRecursion to avoid throwing an exception on recursive references */
    /* no need to specify refs, or path -- they are used interally */
    function deepClone(target, skipRecursion, refs, path) {
      if (!refs) refs = []
      if (!path) path = ''
      if (refs.indexOf(target) > -1) {
        if (skipRecursion) return null
        throw('Recursive reference at ' + path)
      }
      refs.push(target)
      let clone = shallowCopy(target)
      for (i in target) target[i] = deepClone(target, refs, path + '.' + i)
      return clone
    }
    

提交回复
热议问题