关于对象的一些问题

对象属性的深度冻结

let deepFreeze = function(obj){
    
    

    if (typeof obj != 'object') return;
    Object.freeze(obj);
    Object.keys(obj).forEach(propName=>{
    
    
        if(typeof obj[propName] === 'object'){
    
    
            deepFreeze(obj[propName]);
        }
    })
    return obj ;
}

浅拷贝

let obj = {
    
    name:'admin',age:'128',foo:{
    
    id:1001}}

function shallowCodpy(obj){
    
    
   const dist ={
    
    };
   for(let prop in obj){
    
    
      if(obj.hasOwnProperty(prop)){
    
    
         dist[prop]=obj[prop]
      }
   }
   return dist;
}
let obj2 = shallowCodpy(obj);

//obj.foo={id:1002}
//console.log(obj2);//{ name: 'admin', age: '128', foo: { id: 1001 } }

// obj.foo.id = 1003;
// console.log(obj2);//{ name: 'admin', age: '128', foo: { id: 1003 } }



深拷贝

JSON.stringify() 转换 和JSON.parse() 也能实现深拷贝,但是有缺陷,拷贝不了对象的方法。
hasOwnProperty()方法。判断对象属性是否存在,存在返回true。只 判断对象本身,不考虑继承(原型) 父级啥的。


function deepCopy(src) {
    
    
   if (src == null) return null;
   if (src == undefined) return undefined;
   if (typeof src != 'object') return;

   const dist = Array.isArray(src) ? [] : {
    
    };
   for (let prop in src) {
    
    
      if (src.hasOwnProperty(prop)) {
    
    
         if (typeof src[prop] == 'object') {
    
    
            dist[prop] = deepCopy(src[prop])
         } else {
    
    
            dist[prop] = src[dist]
         }

      }
   }
   return dist;
}

猜你喜欢

转载自blog.csdn.net/weixin_45753588/article/details/124620770