FED实验室 - 专注WEB端开发和用户体验

javascript 全类型检查type.js

JAVASCRIPT 煦涵 3047℃ 0评论

涉及 Null,Undefined,Object,Array,String,Number,Boolean,Function,RegExp,Element,NaN,Infinite等数据类型的判断。基本代码实现如下:(已添加forEach在lte IE8下的支持)

(function (root) {
 	var typeArr = [
        'Null',
        'Undefined',
        'Object',
        'Array',
        'String',
        'Number',
        'Boolean',
        'Function',
        'RegExp',
        'Element',
        'NaN',
        'Infinite'
    ],
    type = function (o) {
 		var s = null,
 			type = "";
        // handle null in old IE
        if (o === null) {
            return 'null';
        }

        // handle DOM elements
        if (o && (o.nodeType === 1 || o.nodeType === 9)) {
            return 'element';
        }

        s = Object.prototype.toString.call(o);
        type = s.match(/\[object (.*?)\]/)[1].toLowerCase();
        // handle NaN and Infinity
        if (type === 'number') {
            if (isNaN(o)) {
                return 'nan';
            }
            if (!isFinite(o)) {
                return 'infinity';
            }
        }

        return type;
    };

    //lte IE8
	if(!Array.prototype.forEach) {
		Array.prototype.forEach = function forEach( callback, thisArg ) {
			var T, k;
			if(this == null) {
				throw new TypeError( "this is null or not defined" );
			}
			var O = Object(this);

			// Hack to convert O.length to a UInt32(32位无符号整数)
			var len = O.length >>> 0; 

			if ( {}.toString.call(callback) !== "[object Function]" ) {
				throw new TypeError( callback + " is not a function" );
			}

			if ( thisArg ) {
				T = thisArg;
			}

			k = 0;

			while( k < len ) {
				var kValue;
				if ( Object.prototype.hasOwnProperty.call(O, k) ) {
					kValue = O[ k ];
					// argument list containing kValue, k, and O.
					callback.call( T, kValue, k, O );
				}
				k++;
			}
		};
	}

    //use forEach fn
    typeArr.forEach(function(val,index,arr){
        type['is' + val] = function (o) {
            return type(o) === val.toLowerCase();
        };
    });
    //commonJS
    if (typeof exports === "object" && exports) {
        exports = type;
    }else if (typeof define === "function" && define.amd) {
        define(type);
    }else {
        root.type = type;
    }
})(this);

参考链接:

forEach:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

http://blog.csdn.net/cuew1987/article/details/16363579

 

下面是「FED实验室」的微信公众号二维码,欢迎扫描关注:

FED实验室

行文不易,如有帮助,欢迎打赏!

赞赏支持or喜欢 (0)or分享 (0)
捐赠共勉
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址