JS 真·深度拷贝(deepCopy)

方法:

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)

结果:

你可能感兴趣的:(算法,前端,javascript)