最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JS對(duì)象復(fù)制(深拷貝和淺拷貝)

 更新時(shí)間:2021年04月29日 09:42:58   作者:淺笑·  
這篇文章主要介紹了JS對(duì)象復(fù)制(深拷貝和淺拷貝),并附有詳細(xì)代碼,感興趣的小伙伴們,可以參考下

一、淺拷貝

1、Object.assign(target,source,source...)

a、可支持多個(gè)對(duì)象復(fù)制

b、如果source和target屬性相同 source會(huì)復(fù)制target的屬性

c、target只能為Object對(duì)象

var obj = {a:1,b:2}
undefined
Object.assign({c:3},obj)
{c: 3, a: 1, b: 2}
obj
{a: 1, b: 2} 
兼容性寫法if(Object.assign){//兼容}else{//不兼容}

2、擴(kuò)展運(yùn)算符(spread)

支持將多個(gè)對(duì)象復(fù)制到一個(gè)對(duì)象上“

var obj1 = { foo: "foo" };
var obj2 = { bar: "bar" };
 
var copySpread = { ...obj1, ...obj2 }; // Object {foo: "foo", bar: "bar"}
copySpread 
{foo: "foo", bar: "bar"}
var obj = {a:1,b:2,c:3}
var objs = {...obj}
objs
{a: 1, b: 2, c: 3}
objs.a=10
10
objs
{a: 10, b: 2, c: 3}
obj
{a: 1, b: 2, c: 3}

二、深拷貝

1、使用對(duì)象序列化 JSON.stringify()和JSON.parse()

注意:此方法僅在原對(duì)象包含可序列化值類型且沒有任何循環(huán)引用時(shí)才有效。不可序列化值類型的一個(gè)例子是Date對(duì)象 -JSON.parse只能將其解析為字符串而無法解析回其原始的Date對(duì)象 或者對(duì)象中屬性值為function

var obj = {a:1,b:[1,2,3],c:{e:3},bool:false}
undefined
var objs = JSON.parse(JSON.stringify(obj))
undefined
objs
{a: 1, b: Array(3), c: {…}, bool: false}
objs.bool = true
true
objs
{a: 1, b: Array(3), c: {…}, bool: true}
obj
{a: 1, b: Array(3), c: {…}, bool: false}

2、使用遞歸,對(duì)對(duì)象屬性進(jìn)行判斷

function deepClone(obj) {
  var copy;
 
  // 如果 obj 是 null、undefined 或 不是對(duì)象,直接返回 obj
  // Handle the 3 simple types, and null or undefined
  if (null == obj || "object" != typeof obj) return obj;
 
  // Handle Date
  if (obj instanceof Date) {
    copy = new Date();
    copy.setTime(obj.getTime());
    return copy;
  }
 
  // Handle Array
  if (obj instanceof Array) {
    copy = [];
    for (var i = 0, len = obj.length; i < len; i++) {
        copy[i] = clone(obj[i]);
    }
    return copy;
  }
 
  // Handle Function
  if (obj instanceof Function) {
    copy = function() {
      return obj.apply(this, arguments);
    }
    return copy;
  }
 
  // Handle Object
  if (obj instanceof Object) {
      copy = {};
      for (var attr in obj) {
          if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
      }
      return copy;
  }
 
  throw new Error("Unable to copy obj as type isn't supported " + obj.constructor.name);
}

以上就是JS對(duì)象復(fù)制(深拷貝和淺拷貝)的詳細(xì)內(nèi)容,更多關(guān)于JS的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論

大田县| 安庆市| 织金县| 泗水县| 凤城市| 延津县| 佛坪县| 辽阳县| 云南省| 延津县| 尖扎县| 卓尼县| 石河子市| 曲阜市| 湟源县| 德格县| 洱源县| 郸城县| 卓尼县| 连江县| 崇信县| 平罗县| 萍乡市| 平谷区| 斗六市| 徐闻县| 灵武市| 深泽县| 雷州市| 南召县| 大荔县| 三都| 屯留县| 阳新县| 中宁县| 师宗县| 贡嘎县| 吴川市| 潮安县| 杂多县| 石景山区|