常用判断js数据类型 Jim

通常情况下用typeof 判断就可以了,遇到预知Object类型的情况可以选用instanceof或constructor方法,实在没辙就使用$.type()方法。

一、typeof
alert(typeof a)  ------------> string
alert(typeof b)  ------------> number
alert(typeof c)  ------------> object
alert(typeof d)  ------------> object
alert(typeof e)  ------------> function
alert(typeof f)  ------------> function

typeof无法判断null,因为null的机器码均为0,so用typeof判断null直接当做对象看待

alert(typeof null)  ------------> object
二、判断已知对象类型的方法: instanceof
alert(c instanceof Array) ---------------> true
alert(d instanceof Date) ---------------->true
new Data('2021/11/23') instanceof Data --->true
alert(f instanceof Function) ------------> true
alert(f instanceof function) ------------> false

注:instanceof 后面一定要是对象类型,并且大小写不能错,
原理就是只要右边变量的prototype在左边变量的原型链即可。
三、根据对象的constructor判断: constructor

alert(c.constructor === Array) ----------> true
alert(d.constructor === Date) -----------> true
alert(e.constructor === Function) -------> true
四、通用的Object.prototype.toString
alert(Object.prototype.toString.call(a) === ‘[object String]') -------> true;
alert(Object.prototype.toString.call(b) === ‘[object Number]') -------> true;
alert(Object.prototype.toString.call(c) === ‘[object Array]') -------> true;
alert(Object.prototype.toString.call(d) === ‘[object Date]') -------> true;
alert(Object.prototype.toString.call(e) === ‘[object Function]') -------> true;
alert(Object.prototype.toString.call(f) === ‘[object Function]') -------> true;
五、万能之王jquery.type()---->简写$.type()
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"
原文地址:https://www.cnblogs.com/huoshengmiao/p/15595019.html