JS-真深度拷贝deepCopy

31次阅读

共计 405 个字符,预计需要花费 2 分钟才能阅读完成。

方法:

function deepCopy (data) {
    let dataTmp = undefined

    if (data === null || !(typeof data === 'object')) {dataTmp = data} else {
        let type = data.constructor.name

        type === 'Array' && (dataTmp = [])
        type === 'Object' && (dataTmp = {})

        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)

结果:

正文完
 0