js数据处理-----数据拷贝

一、理解深拷贝与浅拷贝

如下代码,把 a  的值赋给  b ,修改 b 的值会直接修改到  a 的值,这叫浅拷贝。(其实他们修改的是同一个对象)

var a = [1,2,3,4,5];
var b = a;
b[2] = 100;
console.log(a);          //[1,2,100,4,5]
console.log(b);		//[1,2,100,4,5]    

  把 obj1  的值赋给 obj2  ,修改 obj2 的值,不会影响到 obj1 的值  ,这叫深拷贝

var obj1 = [1,2,3,4,5]
var obj2 = [];
for(var i = 0; i < obj1.length; i++){
	obj2.push(obj1[i])
}
obj2[2] = 100
console.log(obj1);      //[1,2,3,4,5]
console.log(obj2)       //[1,2,100,4,5]

  

二、深度拷贝的多种情况

这里我列举以下几种例子,在以下的拷贝方法里也会将各种方法做一个比较,例子如下

var obj1 = {name:"张三",age:18}	
var obj2 = {
	name:"王五",
	intersects:{one:"游泳",two:"看书"},
	getNum: function(){
	  return 10;
	},
	numArr:["猫","狗","鸡"]
}
var arr1 = [1,2,3,4,5,"六","七"]			
var arr2 = [
	{name:"张三",age:18},
	{name:"王五",age:19}
]

  方法一:转为JSON格式

亲测:obj1,arr1,arr2 均有效,obj2无效,

原因:这种方法的缺陷是会破坏原型链,并且无法拷贝属性值为function的属性

var copyObj2 = JSON.parse(JSON.stringify(obj1))
copyObj2.name = "哈哈"

console.log(obj1)        //{name:"张三",age:18}	
console.log(copyObj2)	 //{name:"哈哈",age:18}	

  方法二:采用递归的方式

  亲测均有效

function copy(obj1, obj2) {
	var obj2 = obj2 || {};
	for(var name in obj1) {
		if(typeof obj1[name] === "object") {
			obj2[name] = (obj1[name].constructor === Array) ? [] : {};
			copy(obj1[name], obj2[name]);
		} else {
			obj2[name] = obj1[name];
		}
	}
	return obj2;
}

var copyObj2 = {}
copyObj2 = copy(obj2,copyObj2);
						
copyObj2.getNum = function(){
	return "单身狗"
}
			
console.log(obj2.getNum())        //10
console.log(copyObj2.getNum())	  //单身狗

  

其他方法;

一、假如你用jquery,可以使用$.extend()

  亲测均有效

var copyarr = $.extend(true, [], arr1);		
copyarr[1] = "888"

console.log(copyarr);         //[1,888,3,4,5,六,七]
console.log(arr1);	        //[1,2,3,4,5,六,七]    

  

var copyarr = $.extend(true, {}, obj2);		
copyarr.getNum = function(){
	return "这是测试"
}

console.log(copyarr.getNum());            //这是测试
console.log(obj2.getNum());		 //10

  

posted @ 2018-08-22 17:32  梁小清  阅读(373)  评论(0编辑  收藏  举报