JavaScript: 4种深拷贝的方法JavaScript: 4种深拷贝的方法JavaScript: 4种深拷贝的方法JavaScript: 4种深拷贝的方法
  • 首页
  • 博客
  • 文件
  • 书签
  • 分析
  • 登录
Search
Generic filters

JavaScript: 4种深拷贝的方法

Published by admin at 2022年8月14日
Categories
  • JavaScript
Tags
浅拷贝与深拷贝

浅拷贝是创建一个新对象,这个对象有着原始对象属性值的拷贝。如果属性是基本类型,拷贝的就是基本类型的值,如果属性是引用类型,拷贝的是内存地址 。

如果不进行深拷贝,其中一个对象改变了对象的值,就会影响到另一个对象的值。
深拷贝是将一个对象从内存中完整的拷贝一份出来,从堆内存中开辟一个新的区域存放新对象,且修改新对象不会影响原对象。
1、JSON.parse(JSON.stringify(obj))

一般情况下对普通对象需要进行深拷贝,可以使用这种方法进行深拷贝操作,这种是最简单且代码量最少的深拷贝方法。

let a = {a:1,b:2}
let b = JSON.parse(JSON.stringify(a))
a.a = 11
console.log(a)//{a:1,b:2}
console.log(b)//{a:11,b:2}

1.1 JSON.parse(JSON.stringify(obj))深浅拷贝的缺陷

let a = {
    name: 'Jack',
    age: 18,
    hobbit: ['sing', {type: 'sports', value: 'run'}],
    score: {
        math: 'A',
    },
    run: function() {},
    walk: undefined,
    fly: NaN,
    cy: null,
    date: new Date()
}
let b = JSON.parse(JSON.stringify(a))
console.log(b)
// {
//     age: 18,
//     cy: null,
//     date: "2022-05-15T08:04:06.808Z"
//     fly: null,
//     hobbit: (3) ["dance", "sing", {…}],
//     name: "Jack",
//     score: {math: "A"},
// }

取不到值为 undefined 的 key;如果对象里有函数,函数无法被拷贝下来;无法拷贝copyObj对象原型链上的属性和方法;对象转变为 date 字符串。
2、普通递归函数实现深拷贝

function deepClone(source) {
  if (typeof source !== 'object' || source == null) {
    return source;
  }
  const target = Array.isArray(source) ? [] : {};
  for (const key in source) {
    if (Object.prototype.hasOwnProperty.call(source, key)) {
      if (typeof source[key] === 'object' && source[key] !== null) {
        target[key] = deepClone(source[key]);
      } else {
        target[key] = source[key];
      }
    }
  }
  return target;
}

2.1、解决循环引用和symblo类型

function cloneDeep(source, hash = new WeakMap()) {
  if (typeof source !== 'object' || source === null) {
    return source;
  }
  if (hash.has(source)) {
    return hash.get(source);
  }
  const target = Array.isArray(source) ? [] : {};
  Reflect.ownKeys(source).forEach(key => {
    const val = source[key];
    if (typeof val === 'object' && val != null) {
      target[key] = cloneDeep(val, hash);
    } else {
      target[key] = val;
    }
  })
  return target;
}

3、兼容多种数据类型

const deepClone = (source, cache) => {
  if(!cache){
    cache = new Map() 
  }
  if(source instanceof Object) { // 不考虑跨 iframe
    if(cache.get(source)) { return cache.get(source) }
    let result 
    if(source instanceof Function) {
      if(source.prototype) { // 有 prototype 就是普通函数
        result = function(){ return source.apply(this, arguments) }
      } else {
        result = (...args) => { return source.call(undefined, ...args) }
      }
    } else if(source instanceof Array) {
      result = []
    } else if(source instanceof Date) {
      result = new Date(source - 0)
    } else if(source instanceof RegExp) {
      result = new RegExp(source.source, source.flags)
    } else {
      result = {}
    }
    cache.set(source, result)
    for(let key in source) { 
      if(source.hasOwnProperty(key)){
        result[key] = deepClone(source[key], cache) 
      }
    }
    return result
  } else {
    return source
  }
}

4、jquery.extend()方法

可以使用$.extend进行深拷贝
$.extend(deepCopy, target, object1, [objectN])//第一个参数为true,就是深拷贝

let a = {
    a: 1,
    b: { d:8},
    c: [1, 2, 3]
};
let b = $.extend(true, {}, a);
console.log(a.b.d === b.b.d); // false

4.1、 jQuery.extend 源码

jQuery.extend = jQuery.fn.extend = function () {
    var options, name, src, copy, copyIsArray, clone,
      target = arguments[0] || {},
      i = 1,
      length = arguments.length,
      deep = false;

    if (typeof target === "boolean") {
      deep = target; 
      target = arguments[1] || {};
      i = 2;
    }

    if (typeof target !== "object" && !jQuery.isFunction(target)) {
      target = {};
    }

    if (length === i) {
      target = this;
      --i;
    }

    for (; i < length; i++) {
      if ((options = arguments[i]) != null) {
        for (name in options) {
          src = target[name];
          copy = options[name];

          if (target === copy) {
            continue;
          }

          if (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))) {
            if (copyIsArray) {
              copyIsArray = false;
              clone = src && jQuery.isArray(src) ? src : [];
            } else {
              clone = src && jQuery.isPlainObject(src) ? src : {};
            }

            target[name] = jQuery.extend(deep, clone, copy);

          } else if (copy !== undefined) {
            target[name] = copy;
          }
        }
      }
    }

    return target;
  };

jQuery.extend 函数详解

Jquery的扩展方法extend是我们在写插件的过程中常用的方法,该方法有一些重载原型,在此,我们一起去了解了解。
一、Jquery的扩展方法原型是:

 

 extend(dest,src1,src2,src3...);

它的含义是将src1,src2,src3...合并到dest中,返回值为合并后的dest,由此可以看出该方法合并后,是修改了dest的结构的。如果想要得到合并的结果却又不想修改dest的结构,可以如下使用:

 

  var newSrc=$.extend({},src1,src2,src3...)//也就是将"{}"作为dest参数。

这样就可以将src1,src2,src3...进行合并,然后将合并结果返回给newSrc了。如下例:

 

var result=$.extend({},{name:"Tom",age:21},{name:"Jerry",sex:"Boy"})

那么合并后的结果

 

  result={name:"Jerry",age:21,sex:"Boy"}

也就是说后面的参数如果和前面的参数存在相同的名称,那么后面的会覆盖前面的参数值。

二、省略dest参数
上述的extend方法原型中的dest参数是可以省略的,如果省略了,则该方法就只能有一个src参数,而且是将该src合并到调用extend方法的对象中去,如:
1、$.extend(src)
  该方法就是将src合并到jquery的全局对象中去,如:

 

 $.extend({
  hello:function(){alert('hello');}
  });

就是将hello方法合并到jquery的全局对象中。
2、$.fn.extend(src)
该方法将src合并到jquery的实例对象中去,如:

 

 $.fn.extend({
  hello:function(){alert('hello');}
 });

   就是将hello方法合并到jquery的实例对象中。

  下面例举几个常用的扩展实例:

 

$.extend({net:{}});

   这是在jquery全局对象中扩展一个net命名空间。

 

  $.extend($.net,{
   hello:function(){alert('hello');}
  })

这是将hello方法扩展到之前扩展的Jquery的net命名空间中去。

三、Jquery的extend方法还有一个重载原型:

 

extend(boolean,dest,src1,src2,src3...)

第一个参数boolean代表是否进行深度拷贝,其余参数和前面介绍的一致,什么叫深层拷贝,我们看一个例子:

 

var result=$.extend( true,  {},  
    { name: "John", location: {city: "Boston",county:"USA"} },  
    { last: "Resig", location: {state: "MA",county:"China"} } ); 

我们可以看出src1中嵌套子对象location:{city:"Boston"},src2中也嵌套子对象location:{state:"MA"},第一个深度拷贝参数为true,那么合并后的结果就是:

 

result={name:"John",last:"Resig",
        location:{city:"Boston",state:"MA",county:"China"}}

也就是说它会将src中的嵌套子对象也进行合并,而如果第一个参数boolean为false,我们看看合并的结果是什么,如下:

 

var result=$.extend( false, {},  
{ name: "John", location:{city: "Boston",county:"USA"} },  
{ last: "Resig", location: {state: "MA",county:"China"} }  
                    ); 

那么合并后的结果就是:

 

  result={name:"John",last:"Resig",location:{state:"MA",county:"China"}}

  以上就是$.extend()在项目中经常会使用到的一些细节。

发表回复 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Categories

  • 猫
  • Python
  • MySQL
  • Django
  • Html/CSS
  • JavaScript
  • Vue
  • RegExp
  • php
  • Practice
  • Virtualization
  • Linux
  • Windows
  • Android
  • NAS
  • Software
  • Hardware
  • Network
  • Router
  • Office
  • WordPress
  • SEO
  • English
  • Games
  • Recipes
  • living
  • Memorandum
  • Essays
  • 未分类

归档

©2015-2022 Alaica Blog support@alaica.com