要想解决循环援用,咱们须要借助Set 或者Map 或者 WeekMap类型,来保留对象之间的援用关系

话不多说,间接上代码:

function isObject(obj) {  return (typeof obj === "object" || typeof obj === "function") && obj !== null;}function cloneDeep(source, hash = new Map()) {  if (!isObject(source)) return source;  if (hash.has(source)) return hash.get(source);  var target = Array.isArray(source) ? [] : {};  hash.set(source, target);  for (var key in source) {    if (Object.prototype.hasOwnProperty.call(source, key)) {      if (isObject(source[key])) {        target[key] = cloneDeep(source[key], hash);      } else {        target[key] = source[key];      }    }  }  return target;}

其实浏览器也有解决方案,只不过还未正式公布