文享日志

实现深拷贝

JavaScript

发表于2017年10月07日00:23:23

0条评论 220次阅读

var msg = {
	id : 20151008023 ,
	name :'韩前进',
	age : 22 ,
	major : 'CS',
	sex : 'man',
	other :{
		friend : ['李子敏','王景盛','杨金山'],
		roomrate : {
			one : '班敏超',
			two : '陈雄'
		}
	}
}
var mymsg = [msg,[msg],'han','qina',2,{age:23}]
var isObject = function(obj){
	return Object.prototype.toString.call(obj) === '[object Object]'
}
var isArray = Array.isArray || function(obj){
	return Object.prototype.toString.call(obj) === '[object Array]'
}

var get_keys = function(obj){
	var keys = [];
	for(key in obj){
		if(hasOwnProperty.call(obj,key)){
			keys.push(key);
		}
	}
	return keys;
}

//实现深拷贝
var deepCopy = function(obj){
	var temp ;
	if(isArray(obj)){
		temp = [];
		for(var i = 0 ; i < obj.length ; i++){
			if(isArray(obj[i])||isObject(obj[i])){
				temp.push(deepCopy(obj[i]));
			}else{
				temp.push(obj[i]);
			}
		}
	}else if(isObject(obj)){
		temp = {};
		var keys = get_keys(obj);
		var length = keys.length ;
		for(var i = 0 ; i < length ; i++){
			temp[keys[i]] = deepCopy(obj[keys[i]])
		}
	}else{
		return obj;
	}
	return temp ;
}

console.log(deepCopy(mymsg));
console.log(deepCopy(msg))


👍 0  👎 0
共有0条评论

发表新评论

提交

广告展示

腾讯云推广 阿里云推广