js 判断数据类型

首先看一段ECMA中对Object.prototype.toString的解释:

Object.prototype.toString( )
When the toString method is called, the following steps are taken:

  1. Get the [[Class]] property of this object.
  2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.
  3. Return Result (2)
var typeOf = function() {
        var toString = Object.prototype.toString;
        var types = ['Object','Boolean', 
            'Number', 'String', 'Function', 
            'Array', 'Date', 'RegExp'];
        var map = {};

        for (var i = 0, l = types.length; i < l; i++) {
            var type = types[i];
            map['[object ' + type + ']'] = type.toLowerCase();
        }

        return function(item) {
            if (item === null) return 'null';
            if (item.nodeType) return 'node';
            if (item.length && item.callee) return 'arguments';
            if (typeof item === 'object') return map[toString.call(item)];
            return typeof item;
        };
    }();
window.typeOf = typeOf;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容