基本数据类型检测
返回类型有:number, boolean, string, undefined, object, function
var i = 2; console.log(typeof i); //number
var b = true; console.log(typeof b); //boolean
var s = "hello"; console.log(typeof s); //string
var n = null; console.log(typeof n); //object
var u; console.log(typeof u); //undefined
var o = new Object(); console.log(typeof o); //object
注:typeof NaN
返回的结果是number
引用类型检测
var iO = new Number(2); console.log(iO instanceof Number); //true
var bO = new Boolean(true); console.log(bO instanceof Boolean); //true
var sO = new String("hello"); console.log(sO instanceof String); //true
var a = [1,2,3]; console.log(a instanceof Array); //true
var aO = new Array(1,2,3); console.log(aO instanceof Array); //true
注:用typeof
检测对象类型的结果都为object
, 而用instanceof
检测对应的基本类型的结果均为false
在
aO instanceof Array
中检测aO是否是一个数组时,首先aO必须是一个数组,而且还必须与Array构造函数在同个全局作用域中(Array是window的属性)。如果aO是在另一个fram中定义的数组,则检测结果也为false
所以引用类型检测时应该使用如下方法检测:
function isArray(value){
return Object.prototype.toString.call(value) == "[object Array]";
}