深克隆方法

383 阅读1分钟
// 是否是Object或者Array
function isObjectOrArray(obj) {
  return (
    Object.prototype.toString.call(obj) === "[object Object]" ||
    Object.prototype.toString.call(obj) === "[object Array]"
  );
}
// 深度克隆方法
function deepClone(obj) {
  if (isObjectOrArray(obj)) {
    let newObj = Array.isArray(obj) ? [] : {};
    Object.keys(obj).forEach((key) => {
      newObj[key] = isObjectOrArray(obj[key]) ? deepClone(obj[key]) : obj[key];
    });
    return newObj;
  }
  return obj;
}