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
}
}
js中深浅拷备
于 2021-02-03 15:14:51 首次发布