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

拷贝 #17

Open
RachelRen opened this issue Aug 30, 2018 · 0 comments
Open

拷贝 #17

RachelRen opened this issue Aug 30, 2018 · 0 comments

Comments

@RachelRen
Copy link
Owner

几种数组浅拷贝

1. arr.concat()

2. arr.slice()

3. JSON.parse( JSON.stringify(arr) )

方法1,2 都是浅拷贝,方法三,如果数组中的对象是function,那么就会有问题。

var arr = [function(){
    console.log(a)
}, {
    b: function(){
        console.log(b)
    }
}]

var new_arr = JSON.parse(JSON.stringify(arr));

console.log(new_arr);

深拷贝

function isPlainObj(obj){
	var classToType = {},
		hasOwn = classToType.hasOwnProperty,
		toString = classToType.toString;

	var proto, Cons;
	if(!obj || toString.call(obj) !== "[object Object]"){
		return false;
	}
	proto = Object.getPrototypeOf(obj);
	if (!proto) {
        return true;
    }

	Cons = hasOwn.call(proto, "constructor") && proto.constructor

	return typeof Cons == "function" && hasOwn.toString.call(Cons) == hasOwn.toString.call(Object)
}

function copy(target, obj){
	var clone, copyIsArray;
	if(typeof obj !=="object"){
		return;
	}
	if (typeof target !== 'object' &&  !isFunction(target)) {
        target = {}
    }

    
	for(let key in obj){
		if(obj.hasOwnProperty(key)){
			var copy = obj[key],
				src = target[key];
			if(copy == target){
				continue;
			}
			if(copy && (copyIsArray = Array.isArray(copy) || isPlainObj(copy))){
				if(copyIsArray){
					clone = src && Array.isArray(src) ? src: [];

				}else{
					clone = src && isPlainObj(src) ? src: {};
				}
				
				target[key] = copy(clone, copy);
			}else{
				target[key] = copy;
			}
		}
	}
	return target;
}
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