Skip to content

深拷贝

59 字小于 1 分钟

js

2024-12-28

深拷贝

function deepClone(data) {
    if (typeof data !== 'object' || data == null) {
        return data
    }

    let target = data instanceof Array ? [] : {}
    for (let k in data) {
        if (Object.prototype.hasOwnProperty.call(data, k)) {
            if (typeof data[k] === 'object') {
                target[k] = deepClone(data[k])
            } else {
                target[k] = data[k]
            }
        }
    }

    return target
}