js中深浅拷备

1:深拷贝常用方法:
JSON.parse(JSON.stringify(拷贝的对象))

2:简单递归实现
function isObj(obj) {
    return (typeof obj === 'object' || typeof obj === 'function') && obj !== null
}
function deepCopy(obj) {

    let tempObj = Array.isArray(obj) ? [] : {}
    for(let key in obj) {
        tempObj[key] = isObj(obj[key]) ? deepCopy(obj[key]) : obj[key]
    }
    return tempObj
}

deepCopy(拷贝的对象)

这两种都有一个问题 拷贝对象的方法  正则  事件对象 会有问题。

合并对象(浅拷贝)
Object.assign(target, source1, source2....);
将多个对象合并到目标对象target,至少需要两个参数,参数必须是对象
var target = { a: 1, b: 1 };
var source1 = { b: 2, c: 2 };
var source2 = { c: 3 };
var source3 = { f: 4, d: 5 };
Object.assign(target, source1, source2, source3);
console.log(target)  //还可以去重 {a: 1, b: 2, c: 3, f: 4, d: 5}

克隆
var b = Object.assign({}, source1);  ||  var b = {};   Object.assign(b, source1); 

深拷贝3;
let deepCopyData=function(target){
	function handleWhile(array,callback){
		const length = array.length;
		let index = -1;
		while(++index <length){
			callback(array[index],index)
		}
	}
	function clone(target,map){
		if(target !== null && typeof target === 'object'){
			let result = Object.prototype.toString.call(target) === "[object Array]"?[] : {};
			if(map.has(target)){
				return map.get(target);
			}
			map.set(target,result)
			const keys = Object.prototype.toString.call(target) === "[object Array]"? undefined : Object.keys(target);
			function callback(value,key){
				if(keys){
					key = value;
				}
				result[key]  =clone(target[key],map)
			}
			handleWhile(keys||target,callback)
			return result;
		}else{
			return target;
		}
	}
	let map = new WeakMap();
	const result = clone(target,map);
	map = null;
	return result;
}
//使用如下
let obj = [{name:'ywt1',id:1,say:[1,2,3,4],size:'42'},{test:undefined}]
console.log(obj,'obj')
let newObj = deepCopyData(obj);
newObj[0].id = 0
newObj.age = function(){
	return 15
}
console.log(newObj,'newObj')

//浅拷贝;注:这个是拷贝的哪个博主的
const _shallowClone = (target) => {
	if(typeof target === 'object && object !== null) {
	const constructor = target.constructor 
		if(/^(Function|RegExp|Date|Map|Set)$/i).test(constructor.name)) return target
		let cloneObj = Array.isArray(target) ? [] : {}
		for(prop in target) {
			cloneObj[prop] = target[prop]
		}
		return cloneObj
	}else {
		return target
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值