How to Deep clone in javascript

前端 未结 19 1540
-上瘾入骨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 03:00

    This works for arrays, objects and primitives. Doubly recursive algorithm that switches between two traversal methods:

    const deepClone = (objOrArray) => {
    
      const copyArray = (arr) => {
        let arrayResult = [];
        arr.forEach(el => {
            arrayResult.push(cloneObjOrArray(el));
        });
        return arrayResult;
      }
    
      const copyObj = (obj) => {
        let objResult = {};
        for (key in obj) {
          if (obj.hasOwnProperty(key)) {
            objResult[key] = cloneObjOrArray(obj[key]);
          }
        }
        return objResult;
      }
    
      const cloneObjOrArray = (el) => {
        if (Array.isArray(el)) {
          return copyArray(el);
        } else if (typeof el === 'object') {
          return copyObj(el);
        } else {
          return el;
        }
      }
    
      return cloneObjOrArray(objOrArray);
    }
    

提交回复
热议问题