1.typeof
- typeof的可能返回的六种结果有(number,boolean,string,function,object,undefined)
- typeof返回的结果是字符串类型的
- 可以使用typeof判断变量是否存在(如if(typeof a!=“undefined”){…})
//用法一
typeof(1) //number
typeof(true) //boolean
typeof([1,2,3]) //object
typeof(a) //undefined
typeof(typeof('111')) //string
typeof(null) //object
//用法二-不加括号
typeof 1 //number
.....
2.instanceof
- 因为A instanceof B 可以判断A是不是B的实例,返回一个布尔值,由构造类型判断其类型
- instanceof 后面一定要是对象类型
console.log([1,2,3] instanceof Array) //true
console.log(function (){} instanceof Function) //true
console.log({ a: 666 } instanceof Object) //true
3.使用 toString() 检测对象类型
可以通过 toString() 来获取每个对象的类型。为了每个对象都能通过 Object.prototype.toString() 来检测,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用,传递要检查的对象作为第一个参数,称为 thisArg。
var toString = Object.prototype.toString;
toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]
//Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]
4.对象的contructor判断
所有对象(使用 Object.create(null) 创建的对象除外)都将具有 constructor 属性。在没有显式使用构造函数的情况下,创建的对象(例如对象和数组文本)将具有 constructor 属性,这个属性指向该对象的基本对象构造函数类型。
const o = {}
o.constructor === Object // true
const o = new Object
o.constructor === Object // true
const a = []
a.constructor === Array // true
const a = new Array
a.constructor === Array // true
const n = new Number(3)
n.constructor === Number // true
5.jq中判断数据类型的方法
jQuery提供了一系列工具方法,用来判断数据类型,以弥补JavaScript原生的typeof运算符的不足。以下方法对参数进行判断,返回一个布尔值。
jQuery.isArray();是否为数组
jQuery.isEmptyObject();是否为空对象 (不含可枚举属性)。
jQuery.isFunction():是否为函数
jQuery.isNumberic():是否为数字
jQuery.isPlainObject():是否为使用“{}”或“new Object”生成对象,而不是浏览器原生提供的对象。
jQuery.isWindow(): 是否为window对象;
jQuery.isXMLDoc(): 判断一个DOM节点是否处于XML文档中。