数据类型判断
① typeof:
typeof {} // object
typeof [1,2] // object
判断数据类型,返回表示数据类型的字符串(返回结果只能包括number,boolean,string,function,object,undefined);
使用typeof判断变量是否存在(如if(typeof a!="undefined"){...});
Typeof 运算符的问题是无论引用的对象是什么类型,它都返回object;
②instanceof:
判断已知对象类型的方法,instanceof 后面一定要是对象类型,并且大小写不能错,这个方法适合一些条件选择或分支。
var c= [1,2,3];
console.log(c instanceof Array) //true
// 要判断的变量 instanceof 数据类型
// 如果类型正确 返回true
③根据对象的contructor属性判断:
console.log('数据类型判断' - constructor);
console.log(arr.constructor === Array); //true
console.log(date.constructor === Date); //true
console.log(fn.constructor === Function); //true
④使用Object.prototype.toString.call()检测对象类型(是对象的一个原生原型扩展函数,用来更精确的区分数据类型):
var gettype=Object.prototype.toString
gettype.call('aaaa') 输出 [object String]
gettype.call(2222) 输出 [object Number]
gettype.call(true) 输出 [object Boolean]
gettype.call(undefined) 输出 [object Undefined]
gettype.call(null) 输出 [object Null]
gettype.call({}) 输出 [object Object]
gettype.call([]) 输出 [object Array]
gettype.call(function(){}) 输出 [object Function]
⑤万能的方法:jquery.type()(如果对象是undefined或null,就返回相应的“undefined”或“null”):
jQuery.type( undefined ) === "undefined"
jQuery.type() === "undefined"
jQuery.type( window.notDefined ) === "undefined"
jQuery.type( null ) === "null"
如果对象有一个内部的[[Class]]和一个浏览器的内置对象的 [[Class]] 相同,我们返回相应的 [[Class]] 名字。 (有关此技术的更多细节。 )
jQuery.type( true ) === "boolean"
jQuery.type( 3 ) === "number"
jQuery.type( "test" ) === "string"
jQuery.type( function(){} ) === "function"
jQuery.type( [] ) === "array"
jQuery.type( new Date() ) === "date"
jQuery.type( new Error() ) === "error" // as of jQuery 1.9
jQuery.type( /test/ ) === "regexp"
其他一切都将返回它的类型“object”