拷贝目标:target, 新对象:newObj
第一种写法:
JSON.parse(JSON.stringify(target))复制代码
这种写法比较简单轻便,但是拷贝目标必须遵从JSON的格式,当遇到层级较深,且序列化对象不完全符合JSON格式时,该方法就有些不妥。
let target = {
a: '1',
b: '2',
c: function func() {
console.log('copy test')
}
}
let newObj = JSON.parse(JSON.stringify(target))
// newObj: {a: "1", b: "2"}复制代码
但是,目前在项目不少部分,我都有使用该方法。
第二种写法:
// 深拷贝函数
function deepCopy (target) {
let result
if (target !== null && typeof target === 'object') {
try {
if (Array.isArray(target)) {
result = []
for (let key = 0; key < target.length; key++) {
result[key] = deepCopy(target[key])
}
} else {
result = {}
for (let key in target) {
result[key] = deepCopy(target[key])
}
}
} catch (e) {
return result
}
} else {
result = target
}
return result
}复制代码
这种写法能够避免第一种方法的一些问题。
请大家多多指教