js深拷贝的三种实现方式(js实现深拷贝的方法)

1、利用JSON对象字符串转换方法(对象中不能有函数,值不能是引用的)。

function deepCopy(ele) {
        return JSON.parse(JSON.stringify(ele));
 }
 const obj = {
   a: {
          b: [1, [2, [, 3, 4]], { c: 5 }],
    },
 };
 const newObj = deepCopy(obj);
newObj.a.b[2].c = 6;
console.log(newObj.a.b[2].c, obj.a.b[2].c); // 6 5

2、利用递归遍历的方法

function deepCopy(ele) {
  const type = typeof ele;
  const baseType = [
          "boolean",
          "number",
          "string",
          "undefined",
          "function",
  ];
  if (baseType.indexOf(type) > -1 || ele === null) return ele;
  const newType = Object.prototype.toString.call(ele);
  if (newType === "[object Array]") {
          const len = ele.length;
          if (!len) return [];
          const res = [];
          for (let i in ele) {
            res.push(deepCopy(ele[i]));
          }
          return res;
   }
   if (newType === "[object Object]") {
        if (Object.keys(ele).length === 0) return {};
        const res = {};
    		for (let key in ele) {
        res[key] = deepCopy(ele[key]);
    	}
       return res;
    }
} 
const obj = {
   a: {
          b: [1, [2, [, 3, 4]], { c: 5 }],
    },
 };
const newObj = deepCopy(obj);
newObj.a.b[2].c = 6;
console.log(newObj.a.b[2].c, obj.a.b[2].c); // 6 5
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至624739273@qq.com举报,一经查实,本站将立刻删除。
Like (0)
柳的头像

相关推荐

发表回复

Please Login to Comment
微信
微信
SHARE
TOP
要想花得少,就用购宝。话费电费9折起,官方公众号:购宝