您的位置:首页 > 编程语言 > Java开发

javascrip获取变量的数据类型

2013-08-29 10:58 239 查看
JS基本类型有数字、布尔、字符串和对象类型。

typeof ""  
"string"  
typeof 1  
"number"  
typeof true  
"boolean"  
typeof /^$/  
"object"  
typeof Date  
"function"  
typeof new Date()  
"object"  
typeof {}  
"object"  
typeof []  
"object"


可见除了基本类型string,number,boolean还有function,object



JS常用对象有几种:Number Array Boolean String Date Function RegExp Null Undefined

而声明属性只有 var, 所以当需要判断属性类型时, 会有一些麻烦。

如何判断属性类型呢? 在读jquery源码时,有这么一段

jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {  
        class2type[ "[object " + name + "]" ] = name.toLowerCase();  
    })  
      
        type: function( obj ) {  
            return obj == null ?  
                String( obj ) :  
                class2type[ toString.call(obj) ] || "object";  
        }


实际上这个作用是

Object.prototype.toString.call(true);  
    "[object Boolean]"  
    Object.prototype.toString.call(1);  
    "[object Number]"  
    Object.prototype.toString.call("");  
    "[object String]"  
    Object.prototype.toString.call(function(){});  
    "[object Function]"  
    Object.prototype.toString.call([]);  
    "[object Array]"  
    Object.prototype.toString.call(new Date());  
    "[object Date]"  
    Object.prototype.toString.call(/^$/);  
    "[object RegExp]"  
    Object.prototype.toString.call({});  
    "[object Object]"


按照jquery的用法可以区分这常用的几种数据类型,非常方便。

来自:http://blog.csdn.net/phoenix2121/article/details/7815025
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: