Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

深复制与浅复制 #25

Open
CoolRabbit520 opened this issue Mar 26, 2018 · 0 comments
Open

深复制与浅复制 #25

CoolRabbit520 opened this issue Mar 26, 2018 · 0 comments

Comments

@CoolRabbit520
Copy link
Owner

CoolRabbit520 commented Mar 26, 2018

浅拷贝只复制指向某个对象的指针,而不复制对象本身,新旧对象还是共享同一块内存。但深拷贝会另外创造一个一模一样的对象,新对象跟原对象不共享内存,修改新对象不会改到原对象。

浅复制

浅复制只会将对象的各个属性进行依次复制,并不会进行递归复制,而 JavaScript 存储对象都是存地址的,所以浅复制会导致新旧对象还是共享同一块内存。

浅复制:

 function simpleClone(initalObj) {    
      var obj = {};    
      for ( var i in initalObj) {
        obj[i] = initalObj[i];
      }    
      return obj;
    }

注意:当object只有一层的时候,是深拷贝,例如如下:

var obj1 = { a: 10, b: 20, c: 30 };
var obj2 = Object.assign({}, obj1);
obj2.b = 100;
console.log(obj1);
// { a: 10, b: 20, c: 30 } <-- 沒被改到
console.log(obj2);
// { a: 10, b: 100, c: 30 }

深复制

深复制不仅将原对象的各个属性逐个复制出去,而且将原对象各个属性所包含的对象也依次采用深复制的方法递归复制到新对象上。
方法:

  1. 递归复制
  2. JSON var newObj = JSON.parse(JSON.stringify(obj));
  3. jquery $.extend
var $ = require('jquery');
var obj1 = {
    a: 1,
    b: { f: { g: 1 } },
    c: [1, 2, 3]
};
var obj2 = $.extend(true, {}, obj1);
console.log(obj1.b.f === obj2.b.f);
// false
  1. lodash _.cloneDeep
var _ = require('lodash');
var obj1 = {
    a: 1,
    b: { f: { g: 1 } },
    c: [1, 2, 3]
};
var obj2 = _.cloneDeep(obj1);
console.log(obj1.b.f === obj2.b.f);
// false

深拷贝对象和数组的方法

var deepclone= function(obj){
	if (typeof obj!==="object"){
		return obj;
	}else{
		var newObj=obj.constructor===Array?[]:{};
		if (winodw.JSON){
			newObj=JSON.parse(JSON.stringify(obj));
		}else{
				for(var i in obj){
					newObj[i]=arguments.callee(obj[i]);
			     }
		}
		return newObj;
	}
}

参考资料

  1. 什么是js深拷贝和浅拷贝及其实现方式
  2. javascript中的深拷贝和浅拷贝? - 知乎
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant