对象的深浅拷贝

浅拷贝

   function shallowCopye(oldObj){
        var newObj = {};
        for(item in oldObj){
            if (oldObj.hasOwnProperty(item)) {
                newObj[item] = oldObj[item];
            }
        }
        return newObj
    }

深拷贝

方法1
  function deepCopy(oldObj) {
    var newObj = {};
    for (const key in oldObj) {
        if (object.hasOwnProperty(key)) {
            if (typeof oldObj[key] === 'string' ||
                typeof oldObj[key] === 'number' ||
                typeof oldObj[key] === 'boolean' ||
                oldObj[key] === null ||
                oldObj[key] === undefined
            ) {
                newObj[key] = oldObj[key];
            }else{
                newObj[key] = deepCopy(oldObj[key]);
            }
            
        }
    }
}
方法2
    function deepCopy(oldObj) {
        var newArr = JOSN.parse(JOSN.stringify(oldObj));
        return  newArr
    }

你可能感兴趣的:(对象的深浅拷贝)