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)
結果: