How to Deep clone in javascript

前端 未结 19 1759
-上瘾入骨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:52

    my addition to all the answers

    function deepCopy(arr) {
      if (typeof arr !== 'object') return arr
      if (Array.isArray(arr)) return [...arr].map(deepCopy)
      for (const prop in arr) 
        copy[prop] = deepCopy(arr[prop])
      return copy
    }
    

提交回复
热议问题