JavaScript判断数据类型

时间:14-04-16 栏目:Javascript 作者:zongyan86 评论:0 点击: 2,615 次

无废话篇,不解释。若不能满足您的需求,请自行完善。。可参考下之前发的文章  javascript类型检测

1.

function isNumber(val){
2      return typeof val === 'number' && isFinite(val);
3 }

2.

function isBooleanType(val) {
    return typeof val ==="boolean";
 }

3.

function isStringType(val) {
        return typeof val === "string";
}

4.

 function isUndefined(val) {
       return typeof val === "undefined";
 }

5.

function isObj(str){
       if(str === null || typeof str === 'undefined'){
            return false;
        }
      return typeof str === 'object';
   }

6.

function isNull(val){
      return  val === null;
 }

7.

 function isArray1(arr) {
    return Object.prototype.toString.apply(arr) === '[object Array]';
 }


 function isArray2(arr) {
    if(arr === null || typeof arr === 'undefined'){
       return false;
     }
     return arr.constructor === Array;
}

总结:

var testType = {
    isType: function (typename, value) {
        //typename:String, Array, Boolean, Object, RegExp, Date, Function,Number //兼容
        //typename:Null, Undefined,Arguments    //IE不兼容
        return Object.prototype.toString.apply(value) === '[object ' + typename + ']';
    },
    isUndefined: function (obj) {
        ///<summary>是否定义</summary>
 
        return (typeof (obj) === "undefined" || obj === undefined);
    },
    isNull: function (obj) {
        ///<summary>是否Null</summary>
 
        return (obj === null || this.isUndefined(obj));
    },
    isBoolean: function (obj) {
        return this.isType("Boolean", obj);
    },
    isObjectEmpty: function (obj) {
        if (this.isNull(obj)) return true;
        for (var n in obj) {
            if (!obj.hasOwnProperty(n)) continue;
            return false;
        }
        return true;
    },
    isNullEmpty: function (s) {
        return (this.isNull(s) || s === '');
    },
    isFunction: function (fun) {
        return this.isType("Function", fun);
    },
    isNumeric: function (n) {
        //return this.isType("Number", n) && !isNaN(n) && isFinite(n);;
        return !isNaN(parseFloat(n)) && isFinite(n);
    },
    isString: function (obj) {
        return this.isType("String", obj);
    },
    isObject: function (obj) {
        return !this.isNull(obj) && this.isType("Object", obj);
    },
    isArray: function (value) {
        return Array.isArray ? Array.isArray(value) : this.isType("Array", value);
    },
    isJquery: function (obj) {
        return (obj instanceof window.jQuery);
    },
    isWindow: function (obj) { return !this.isNull(obj) && obj == obj.window },
    isElement: function (obj) { var t = obj && (obj.ownerDocument || obj).documentElement; return t ? true : false }
};

web开发分享



声明: 本文由( zongyan86 )原创编译,转载请保留链接: JavaScript判断数据类型

关注我们