如何在jQuery中使用$.extend(true,object1, object2)深拷贝对象

如何在jQuery中使用$.extend(true,object1, object2)深拷贝对象?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

语法:jQuery.extend( [deep ], target, object1 [, objectN ] )

深浅拷贝对应的参数就是[deep],是可选的,为true或false。默认情况是false(浅拷贝),并且false是不能够显示的写出来的。如果想写,只能写true(深拷贝)

测试例子:

var object1 = {};
var object2 = {
  b:{
    mm:333
  },
  c:100
};
console.log('原来的object1--->'+JSON.stringify(object1));
console.log('原来的object2--->'+JSON.stringify(object2));
$.extend(true,object1, object2);
object1.b.mm = 600;
console.log('新的object1--->'+JSON.stringify(object1));
console.log('新的object2--->'+JSON.stringify(object2));

测试结果

如何在jQuery中使用$.extend(true,object1, object2)深拷贝对象

由测试结果知道,jQuery中$.extend(true,object1, object2);可以深拷贝对象,拷贝之后,改变其中一个对象的属性值,对另外一个没有影响。

接着在继续深入理解

测试例子

var object1 = {
  a: 0,
  b: {
    gg: 11,
    mm: 22
  }
};
var object2 = {
  b: {
    mm: 333
  },
  c: 100
};
//默认情况浅拷贝
//object1--->{"apple":0,"banana":{"price":200},"cherry":97,"durian":100}
//object2的banner覆盖了object1的banner,但是weight属性未被继承
//$.extend(object1, object2);
//深拷贝
//object1--->{"apple":0,"banana":{"weight":52,"price":200},"cherry":97,"durian":100}
//object2的banner覆盖了object1的banner,但是weight属性也被继承了呦
$.extend(true,object1, object2);
console.log('原来的object1--->'+JSON.stringify(object1));
console.log('原来的object2--->'+JSON.stringify(object2));
object1.b.mm = 600;
console.log('新的object1--->'+JSON.stringify(object1));
console.log('新的object2--->'+JSON.stringify(object2));

测试结果

如何在jQuery中使用$.extend(true,object1, object2)深拷贝对象

看完上述内容,你们掌握如何在jQuery中使用$.extend(true,object1, object2)深拷贝对象的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!