久久久久久久视色,久久电影免费精品,中文亚洲欧美乱码在线观看,在线免费播放AV片

<center id="vfaef"><input id="vfaef"><table id="vfaef"></table></input></center>

    <p id="vfaef"><kbd id="vfaef"></kbd></p>

    
    
    <pre id="vfaef"><u id="vfaef"></u></pre>

      <thead id="vfaef"><input id="vfaef"></input></thead>

    1. 站長資訊網(wǎng)
      最全最豐富的資訊網(wǎng)站

      JS 深拷貝的三種實現(xiàn)方式

      JS 深拷貝的三種實現(xiàn)方式

      JS 深拷貝的三種實現(xiàn)方式

      1、將對象轉(zhuǎn)換為JSON字符串形式,再將其轉(zhuǎn)換為原生JS對象;

      //_tmp和result是相互獨立的,沒有任何聯(lián)系,有各自的存儲空間。 let deepClone = function (obj) {     let _tmp = JSON.stringify(obj);//將對象轉(zhuǎn)換為json字符串形式     let result = JSON.parse(_tmp);//將轉(zhuǎn)換而來的字符串轉(zhuǎn)換為原生js對象     return result; };  let obj1 = {     weiqiujaun: {         age: 20,         class: 1502     },     liuxiaotian: {         age: 21,         class: 1501     } };  let test = deepClone(obj1); console.log(test);

      2、使用JS中的for循環(huán)實現(xiàn)遍歷和復(fù)制;

      function deepClone(obj) {     let result = typeof  obj.splice === "function" ? [] : {};     if (obj && typeof obj === 'object') {         for (let key in obj) {             if (obj[key] && typeof obj[key] === 'object') {                 result[key] = deepClone(obj[key]);//如果對象的屬性值為object的時候,遞歸調(diào)用deepClone,即在吧某個值對象復(fù)制一份到新的對象的對應(yīng)值中。             } else {                 result[key] = obj[key];//如果對象的屬性值不為object的時候,直接復(fù)制參數(shù)對象的每一個鍵值到新的對象對應(yīng)的鍵值對中。             }          }         return result;     }     return obj; }  let testArray = ["a", "b", "c", "d"]; let testRes = deepClone(testArray); console.log(testRes); console.log(typeof testRes[1]);  let testObj = {     name: "weiqiujuan",     sex: "girl",     age: 22,     favorite: "play",     family: {brother: "son", mother: "haha", father: "heihei"} }; let testRes2 = deepClone(testObj); testRes2.family.brother = "weibo"; console.log(testRes2);

      3、利用數(shù)組的“Array.prototype.forEach”方法進行復(fù)制即可實現(xiàn)深拷貝。

      let deepClone = function (obj) {     let copy = Object.create(Object.getPrototypeOf(obj));     let propNames = Object.getOwnPropertyNames(obj);     propNames.forEach(function (items) {         let item = Object.getOwnPropertyDescriptor(obj, items);         Object.defineProperty(copy, items, item);      });     return copy; };  let testObj = {     name: "weiqiujuan",     sex: "girl",     age: 22,     favorite: "play",     family: {brother: "wei", mother: "haha", father: "heihei"} } let testRes2 = deepClone(testObj); console.log(testRes2);

      推薦教程:《JS教程》

      贊(0)
      分享到: 更多 (0)
      網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號