判断数据类型的几种方式
2019-07-05
1. typeof
可以判断数据类型,它返回表示数据类型的字符串(返回结果只能包括 number,boolean,string,function,object,undefined);
可以使用 typeof 判断变量是否存在(如 if(typeof a!=”undefined”){…});
Typeof 运算符的问题是无论引用的对象是什么类型 它都返回 object
1 2 3
| typeof {}; typeof [1, 2]; typeof /\s/;
|
2.instanceof
原理 因为 A instanceof B 可以判断 A 是不是 B 的实例,返回一个布尔值,由构造类型判断出数据类型
1 2 3 4
| console.log(arr instanceof Array); console.log(date instanceof Date); console.log(fn instanceof Function);
|
3.通过 Object 下的 toString.call()方法来判断
1 2 3 4 5 6 7 8
| Object.prototype.toString.call(); console.log(toString.call(123)); console.log(toString.call("123")); console.log(toString.call(undefined)); console.log(toString.call(true)); console.log(toString.call({})); console.log(toString.call([])); console.log(toString.call(function () {}));
|
4.根据对象的 contructor 判断
1 2 3 4
| console.log("数据类型判断" - constructor); console.log(arr.constructor === Array); //true console.log(date.constructor === Date); //true console.log(fn.constructor === Function); //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 文档中。