今天做某个项目,需要函数深拷贝。

在网上随便找了个代码粘上去,结果报错了。

/**
     *
     * @desc   递归法 对象深拷贝
     * @param  {Object}
     * @return {new Object}
     */
    static objectCopy (obj) {
        var newobj = obj.constructor === Array ? [] : {};
        if(typeof obj !== 'object'){
            return;
        }
        for(var i in obj){
           newobj[i] = typeof obj[i] === 'object' ?
           this.objectCopy(obj[i]) : obj[i];
        }
        return newobj
    }

开始的时候一脸懵逼,后来想起来了:typeof null 有个bug,而在我的项目中需要用这个方法的对象有的值是null。

typeof null // "object"

即:

typeof null === “object” // true

这是js一个经典bug。

 

所以这个方法得稍微改一下。

/**
     *
     * @desc   递归法 对象深拷贝
     * @param  {Object}
     * @return {new Object}
     */
    static objectCopy (obj) {
        var newobj = obj.constructor === Array ? [] : {};
        if(typeof obj !== 'object'){
            return;
        }
        for(var i in obj){
           newobj[i] = (typeof obj[i] === 'object' && !(obj[i] === null)) ?
           this.objectCopy(obj[i]) : obj[i];
        }
        return newobj
    }

红色的部分就是修改后的部分。

以上。

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-14
  • 2021-08-04
  • 2022-12-23
  • 2021-07-26
  • 2021-07-28
猜你喜欢
  • 2022-12-23
  • 2021-11-16
  • 2022-12-23
  • 2022-12-23
  • 2021-09-04
  • 2022-01-01
  • 2021-11-17
相关资源
相似解决方案