浅拷贝和深拷贝

112 阅读1分钟

面试老是被问到,直接背代码

浅拷贝

这个要点在于只拷贝变量的值,无论是原始类型还是引用类型

// es5
function shallowClone(obj){
            if (typeof obj === "object"){
                const newObj = Array.isArray(obj) ? [] : {}
                for (const newObjKey in newObj) {
                    newObj[newObjKey] = newObj[newObjKey]
                }
            }else {
                return obj
            }
        }
// es6
function shallowClone(obj){
   return Array.isArray(obj) ? [...obj] : {...obj}
}
function shallowClone(obj){
    return Object.assign({},obj)
}

深拷贝

//JSON
JSON.parse(JSON.stringfy(obj))
// JavaScript
function deepClone(obj) {
            if (obj === null) return obj;
            if (typeof obj !== "object") return obj;
            let cloneObj = Array.isArray(obj) ? [] : {}
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                    cloneObj[key] = deepClone(obj[key]);
                }
            }
            return cloneObj;
        }

足够应付面试了