banner
SlhwSR

SlhwSR

热爱技术的一名全栈开发者
github
bilibili

Besides recursion, what other ways are there to achieve deep copy?

In addition to recursion, iteration can also be used to achieve deep copy. Specifically, a stack can be used to store the objects that need to be processed, and then in a loop, objects are continuously popped from the stack and copied until the stack is empty.

Here is an example code that uses iteration to achieve deep copy:


function deepClone(obj) {
  let stack = [obj];
  let copy = {};

  while (stack.length) {
    let cur = stack.pop();

    for (let key in cur) {
      if (cur.hasOwnProperty(key)) {
        let value = cur[key];
        if (typeof value === 'object') {
          // Handling arrays
          if (Array.isArray(value)) {
            copy[key] = [];
            for (let i = 0; i < value.length; i++) {
              copy[key][i] = value[i];
              if (typeof value[i] === 'object') {
                stack.push(value[i]);
              }
            }
          }
          // Handling objects
          else {
            copy[key] = {};
            for (let k in value) {
              copy[key][k] = value[k];
              if (typeof value[k] === 'object') {
                stack.push(value[k]);
              }
            }
          }
        } else {
          copy[key] = value;
        }
      }
    }
  }

  return copy;
}

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.