zoukankan      html  css  js  c++  java
  • 一个深拷贝方法的漏洞与一个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
        }

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

    以上。

  • 相关阅读:
    clickhouse使用docker安装单机版
    nacos使用docker安装单机版
    第三周学习进度
    第二周学习进度
    二柱子四则运算定制版
    课堂测试小程序
    学习进度
    阅读计划
    自我介绍
    寻找水王
  • 原文地址:https://www.cnblogs.com/foxcharon/p/10408415.html
Copyright © 2011-2022 走看看