对象的深浅拷贝

2017-05-22  本文已影响0人  8d2855a6c5d0

浅拷贝

   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
    }
上一篇下一篇

猜你喜欢

热点阅读