使用结构化克隆算法克隆复杂对象

const clone = (obj) => {
  const id = Date.now();
  return new Promise((resolve, reject) => {
    const onMessage = (e) => {
      if (e && e.data && e.data.id === id) {
        resolve(e.data.obj);
        window.removeEventListener("message", onMessage);
      }
    };
    window.addEventListener("message", onMessage);
    window.postMessage({
      id: id,
      obj: obj,
    });
  });
};

clone({
  date: new Date(),
  reg: /\d+/,
  child: {
    arr: [
      1,
      3,
      new Map(
        Object.entries({
          apple: "red",
        })
      ),
    ],
  },
}).then(console.log);

参考