一个深拷贝方法的漏洞与一个javascript经典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' ?
           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
    }

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

以上。

原文地址:https://www.cnblogs.com/foxcharon/p/10408415.html