js对象深拷贝

200 阅读1分钟
            function myTypeOf (obj) { // 判断数据类型
                return Object.prototype.toString.call(obj)
            }


            function copyObj (obj) { // 深拷贝方法
                const type = myTypeOf(obj)
                if (type === '[object Object]') {
                    const newObj = {}
                    for (var key in obj) {
                        newObj[key] = copyObj(obj[key])
                    }
                    return newObj
                } else if (type === '[object Array]') {
                    const arr = []
                    for (var i = 0; i < obj.length; i++) {
                        arr[i] = copyObj(obj[i])
                    }
                    return arr
                } else { // 此时可能是 number string boolen undefined null  直接返回即可
                    return obj
                }
            }

            // 示例

            const obj = {a: {b:{c: 6}}}

            const obj2 = copyObj(obj)

            obj2.a.b.c = 9

            console.log(obj,obj2)