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的用法可以区分这常用的几种数据类型,非常方便。