判断变量类型
2021-08-17 本文已影响0人
WANG_M
在 JS 中,有 5 种基本数据类型和 1 种复杂数据类型
基本数据类型:Undefined, Null, Boolean, Number和String
复杂数据类型:Object,Object中还细分了很多具体的类型,比如:Array, Function, Date等等
1.typeof
- 可以判断数据类型,它返回表示数据类型的字符串(返回结果只能包括number,boolean,string,function,object,undefined);
- 可以使用typeof判断变量是否存在(如if(typeof a!="undefined"){...});
- typeof 运算符的问题是无论引用的对象Arr、Function、Date等等,它都返回object。
var m = 123;
var l = [11,22];
console.log(typeof m,typeof l); //number,object
2.instanceof
instanceof 方法要求开发者明确地确认对象为某特定类型。
也就是A instanceof B 可以判断A是不是B的实例,返回一个布尔值,由构造类型判断出数据类型。
function fruit(){
}
var apple = new fruit();
console.log(apple instanceof fruit);//true
3. 使用constructor检测
constructor本来是原型对象上的属性,指向构造函数。但是根据实例对象寻找属性的顺序,若实例对象上没有实例属性或方法时,就去原型链上寻找,因此,实例对象也是能使用constructor属性的。
console.log('数据类型判断' - constructor);
console.log(arr.constructor === Array); //true
console.log(date.constructor === Date); //true
console.log(fn.constructor === Function); //true
4. 使用Object.prototype.toString.call
var m = [11,22,33]
console.log(Object.prototype.toString.call(m));//[object Array]
Object.prototype.toString.call(变量)输出的是一个字符串,字符串里有一个数组,第一个参数是Object,第二个参数就是这个变量的类型,而且,所有变量的类型都检测出来了,我们只需要取出第二个参数即可
5. jquery中$.type的实现jQuery提供了一系列工具方法,用来判断数据类型,以弥补JavaScript原生的typeof运算符的不足。以下方法对参数进行判断,返回一个布尔值。
jQuery.isArray();是否为数组
jQuery.isEmptyObject();是否为空对象 (不含可枚举属性)。
jQuery.isFunction():是否为函数
jQuery.isNumberic():是否为数字
jQuery.isPlainObject():是否为使用“{}”或“new Object”生成对象,而不是浏览器原生提供的对象。
jQuery.isWindow(): 是否为window对象;
jQuery.isXMLDoc(): 判断一个DOM节点是否处于XML文档中。