欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS對(duì)象的深度克隆方法示例

 更新時(shí)間:2017年03月16日 12:05:29   作者:lemon678  
這篇文章主要介紹了JS對(duì)象的深度克隆方法,結(jié)合實(shí)例形式分析了JavaScript深度克隆的實(shí)現(xiàn)技巧,需要的朋友可以參考下

本文實(shí)例講述了JS對(duì)象的深度克隆方法。分享給大家供大家參考,具體如下:

js中創(chuàng)建的對(duì)象指向內(nèi)存,所以在開(kāi)發(fā)過(guò)程中,往往修改了一個(gè)對(duì)象的屬性,會(huì)影響另外一個(gè)對(duì)象。

尤其是在angular框架中,dom是由數(shù)據(jù)驅(qū)動(dòng)的,在增刪改查對(duì)象的操作中,對(duì)象屬性的繼承關(guān)系是很讓人頭痛的!

我之前遇到的問(wèn)題就是,在編輯頁(yè)面,操作了對(duì)象數(shù)據(jù),影響到了展示數(shù)據(jù)的展現(xiàn)!

我整理了兩種深度克隆對(duì)象的方法,供大家參考!

首先var 一個(gè)假數(shù)據(jù)

復(fù)制代碼 代碼如下:
var schedule = {"status":21,"msg":"ok","data":[{"name":"lemon","age":21,"contactList":{"phone":[152,153,154],"email":5295}},{"name":"lara","age":22,"contact":{"phone":152,"email":5295}}]}

方法1:

遍歷自身,判斷當(dāng)前對(duì)象是obj還是list,克隆出新對(duì)象

function deepClone(obj)
{
  var o,i,j,k;
  if(typeof(obj)!="object" || obj===null)return obj;
  if(obj instanceof(Array))
  {
    o=[];
    i=0;j=obj.length;
    for(;i<j;i++)
    {
      if(typeof(obj[i])=="object" && obj[i]!=null)
      {
        o[i]=arguments.callee(obj[i]);
      }
      else
      {
        o[i]=obj[i];
      }
    }
  }
  else
  {
    o={};
    for(i in obj)
    {
      if(typeof(obj[i])=="object" && obj[i]!=null)
      {
        o[i]=arguments.callee(obj[i]);
      }
      else
      {
        o[i]=obj[i];
      }
    }
  }
  return o;
}
var scheduleClone = deepClone(schedule)
scheduleClone.data[0].contactList.phone[0] = 99999999999
console.log('方法1 深度克隆')
console.log(scheduleClone)
console.log(JSON.stringify(schedule))
console.log(JSON.stringify(scheduleClone))

方法2:

用js原生的json序列化的方式,簡(jiǎn)單粗暴!

var scheduleClone2 = JSON.parse(JSON.stringify(schedule));
console.log('方法2 深度克隆')
console.log(scheduleClone2)
scheduleClone2.data[0].contactList.phone[0] = 8888888
console.log(JSON.stringify(schedule))
console.log(JSON.stringify(scheduleClone2))

更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《javascript面向?qū)ο笕腴T教程》、《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)

希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論