美文网首页
js 判断数据类型

js 判断数据类型

作者: moxhuis | 来源:发表于2015-08-01 08:58 被阅读0次

首先看一段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;

相关文章

网友评论

      本文标题:js 判断数据类型

      本文链接:https://www.haomeiwen.com/subject/evcvqttx.html