zoukankan      html  css  js  c++  java
  • 有趣的代码: fixTypeof

    typeof 可以匹配对象的类型,但是他的能力很弱,比如 typeof new String('123')会显示的object这是我们不想看到的结果很久以前JQ的作者通过Object.prototype.toString.call(name)这逆天的方法帮我们指明的道路.

    
        function fixTyoeof(obj){
            var retVal;
            //由于typeof null 也会是object我们这里去排除
            if(obj === null)
                return 'null';
            //Math我们也去排除
            if(obj === Math)
                return 'Math';
            retVal = typeof obj
            if(retVal === 'object'){
                switch(obj.constructor){
                    case String:
                        return 'string';
                    case Number:
                        return 'number';
                    case Boolean:
                        return 'boolean';
                    case Array:
                        return 'array';
                    case Date:
                        return 'date';
                    case RegExp:
                        return 'regExp';
                }
            }
            return retVal;
        }
    function fixTyoeof(key){
        switch(Object.prototype.toString.call(key)){
            case '[object Array]'         : return 'Array';
            case '[object String]'         : return 'String';
            case '[object RegExp]'         : return 'RegExp';
            case '[object Number]'         : return 'Number';
            case '[object Function]'    : return 'Function';
            case '[object Boolean]'     : return 'Boolean';
            case '[object Math]'        : return 'Math';
            case '[object Date]'        : return 'Date';
            default :
                //由于 IE678 null undefined 会显示[object Object] 所以我们直接匹配
                switch(key){
                    case null             : return 'Null';
                    case undefined         : return 'Undefined';
                    default             : return 'Object';
                }
        }
    }

    第一版是通过 constructor 去识别,第二版是通过逆天的Object.prototype.toString.call(name)方法

  • 相关阅读:
    oauth
    web api Authorization
    sql 找到前三
    js计算误差修正代码(真实版)
    js操作keyframes动态赋值
    元素拖拽缩放的jquery插件
    js生成组织结构树(原创)
    js图片拖拽、缩放、添加图层功能(原创)
    for循环,forin循环和Array.every(),obj.forEach()方法运行速度对比
    for循环+forin循环生成内容模版
  • 原文地址:https://www.cnblogs.com/somesayss/p/3633197.html
Copyright © 2011-2022 走看看