深拷贝
function getType(data) {
// t:Object Array Null Undefined Date RegExp Function Number Boolean String
const t = Object.prototype.toString.call(data)
return t.slice(8, -1)
}
// 深拷贝
// [1,2,3,[1,2,3]]
// {a:1,b:2,c:3,{x:1}}
// 特殊处理:RegExp/时间格式/构造函数
// 循环引用?let a={x:b} let b={x:a}
export defult function cloneDeep(data) {
const type = getType(data)
if (data === null || typeof data !== 'object') {
return data
} else if (type === 'Function') {
return new Function("return " + data.toString())
} else if (type === 'Date') {
return new Date(data)
} else {
const x = type === 'Array' ? [] : {}
let value
for (const key in data) {
value = data[key]
if (value === data) {
continue
}
const temp = cloneDeep(value)
x[key] = temp
}
return x
}
}
浅拷贝
js中4种浅拷贝方法
let obj_old = { name: 'Tom', age: 15, favorite: { food: 'bread', drink: 'milk' } }
1.语法:Object.assign(target, ...sources)
target 目标对象,接收源对象属性的对象,也是修改后的返回值。 sources 源对象,包含将被合并的属性。
let obj_new = {...obj_old}
2.语法:{...sources}
sources 源对象,包含将被合并的属性。
let obj_new = Object.assign({}, obj_old)
3.语法:arr.concat(value0, /* … ,*/ valueN)
注:如果省略了所有 valueN 参数,则 concat 会返回调用此方法的现存数组的一个浅拷贝。
let arr_new = arr_old.concat()
4.语法:arr.slice(begin, end)
注:如果省略了 begin, end 参数,则 slice 会返回调用此方法的现存数组的一个浅拷贝。
let arr_new = arr_old.slice()
console.log(obj_old === obj_new) // false
console.log(obj_old.name === obj_new.name) // true
console.log(obj_old.favorite === obj_new.favorite) // true