Giter Site home page Giter Site logo

实现一个深拷贝 about blog HOT 2 OPEN

swiftwind0405 avatar swiftwind0405 commented on July 30, 2024
实现一个深拷贝

from blog.

Comments (2)

swiftwind0405 avatar swiftwind0405 commented on July 30, 2024

待读文章:

from blog.

swiftwind0405 avatar swiftwind0405 commented on July 30, 2024

递归实现一个深拷贝

const target = {
  field1: 1,
  field2: undefined,
  field3: {
    child: "child",
  },

  field4: [2, 4, 8],
};

target.target = target;

实现:

function clone(target, map = new WeakMap()) {
  if (typeof target === "object") {
    let cloneTarget = Array.isArray(target) ? [] : {};

    if (map.get(target)) {
      return;
      map.get(target);
    }

    map.set(target, cloneTarget);

    for (const key in target) {
      cloneTarget[key] = clone(target[key], map);
    }

    return;
    cloneTarget;
  } else {
    return;
    target;
  }
}

深拷贝也是递归常考的例子

每次拷贝发生的事:

  • 检查 map 中有无克隆过的对象
  • 有,直接返回
  • 没有, 将当前对象作为 key,克隆对象作为 value 进行存储
  • 继续克隆

在这段代码中我们使用了 weakMap ,用来防止因循环引用而出现的爆栈。

from blog.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.