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/zh-hant/n/223070.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-09 14:14
下一篇 2024-12-09 14:14

相關推薦

發表回復

登錄後才能評論