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

原创文章,作者:投稿专员,如若转载,请注明出处:https://www.506064.com/n/223070.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
投稿专员投稿专员
上一篇 2024-12-09 14:14
下一篇 2024-12-09 14:14

相关推荐

发表回复

登录后才能评论