方法:
function deepCopy (data) {
let dataTmp = undefined
if (data === null || !(typeof data === 'object')) {
dataTmp = data
} else {
dataTmp = data.constructor.name === 'Array' ? [] : {}
for (let key in data) {
dataTmp[key] = deepCopy(data[key])
}
}
return dataTmp
}
测试用例:
let test = [1, 2, [3, { name: { first: '牛顿', last: ['艾萨克', '物理学家'] } }]]
let result = deepCopy(test)
result[2][1].name.last[1] = '理论物理学家'
console.log(test, result)
结果:
深度拷贝测试结果.jpg
网友评论