Advanced-Frontend / Daily-Interview-Question

我是依扬(木易杨),公众号「高级前端进阶」作者,每天搞定一道前端大厂面试题,祝大家天天进步,一年后会看到不一样的自己。
https://muyiy.cn/question/
27.39k stars 3.29k forks source link

看了几个广度优先的都不对,自己写一个 #556

Closed playjump closed 2 years ago

playjump commented 2 years ago
function deepClone(src) {
  if (typeof src !== "object") {
    return src;
  }

  function clone(src, target) {
    const cplist = [];
    for (const key in src) {
      if (typeof src[key] === "object") {
        target[key] = new src[key].constructor();
        cplist.push([src[key], target[key]]);
      } else {
        target[key] = src[key];
      }
    }

    return cplist;
  }

  const result = new src.constructor();
  let cplist = clone(src, result);
  while (cplist.length) {
    let newList = [];
    for (const value of cplist) {
      newList = newList.concat(clone(value[0], value[1]));
    }

    cplist = newList;
  }

  return result;
}