美文网首页
手写深拷贝方法

手写深拷贝方法

作者: 我没叫阿 | 来源:发表于2023-06-15 09:24 被阅读0次
        // 手写深拷贝
        function deepClone(source) {
            // 1.判断传入的值是 Array 还是 Object 
            const targetObj = source.constructor === Array ? [] : {}
            for (const key in source) {
                if (source.hasOwnProperty(key)) {
                    if (source[key] && typeof source[key] === 'object') {
                        // 引用数据类型
                        targetObj[key] = source[key].constructor === Array ? [] : {}
                        targetObj[key] = deepClone(source[key])
                    } else {
                        // 基本数据类型
                        targetObj[key] = source[key]
                    }
                }
            }
            return targetObj
        }

        let obj = {
            name: '张三',
            age: 18,
            student: [{name: '小明'}],
        }

        let newObj = obj
        newObj.name = "李四"
        newObj.student = {}
        console.log(obj===newObj); // true

相关文章

网友评论

      本文标题:手写深拷贝方法

      本文链接:https://www.haomeiwen.com/subject/ryxlydtx.html