前言
本文整理了js中判断数据类型的六种方式,如果对答案有不一样见解的同学欢迎评论区补充讨论,当然有问题,也欢迎在评论区指出。
1.对象的contructor
undefined和null(会报错)
console.log(arr.constructor === Array); //true 返回的是数据类型
console.log(arr.constructor === Object); //false,注意
console.log(date.constructor === Date); //true
console.log(fn.constructor === Function); //true
2.Object.prototype.toString.call()(能准确判断)
NumberObject.toString(radix) ------ radix设置2时,转化为二进制
//Object.prototype.toString.call(arr) === ‘[object Array]’ 用来判断
console.log(toString.call(123)); //[object Number]
console.log(toString.call('123')); //[object String]
console.log(toString.call(undefined)); //[object Undefined]
console.log(toString.call(true)); //[object Boolean]
console.log(toString.call({})); //[object Object]
console.log(toString.call([])); //[object Array]
console.log(toString.call(function(){})); //[object Function]
//注意
console.log(Object.prototype.toString.call((function() {
return 'hzy';
})())); //[object String]
console.log(Object.prototype.toString.call((function() {
return 'hzy';
}))); //[object Function]
3. typeof
- 返回表示数据类型的字符串(返回结果只能包括number,boolean,string,function,object,undefined);只能判断基础类型,null array object 都是object
- 可以使用typeof判断变量是否存在
- Typeof 问题是无论引用的对象是什么类型,它都返回object
console.log(typeof arr) //undefined,变量arr未定义
typeof {} // object
typeof [1,2] // object
typeof /\s/ //object
4.instanceof
- 基于原型实现,不能检测基本类型,除非是字符串对象和布尔对象,只能判断对象类型或引用类型)
- arr(变量) instanceof Array(数据类型)
let str1 = new String('333')
let str2 = new String('333')+'7'
console.log(str1 instanceof String,str1); //true [String: '333']
console.log(str2 instanceof String,str2); //false 3337
console.log(arr instanceof Array ); // true
console.log(arr instanceof Object ); // true 即会把数组当做Array类型,又会把数组当做Object类型
//注意: instanceof 后面一定要是对象类型,大小写不能写错
function fn(){
return 1;
}
let date = new Date()
console.log(date instanceof Date ); // true
console.log(fn instanceof Function ); // true
5.JQuery判断
jQuery提供了一系列工具方法,用来判断数据类型,以弥补JavaScript原生的typeof运算符的不足。以下方法对参数进行判断,返回一个布尔值。
- jQuery.isArray();是否为数组
- jQuery.isEmptyObject();是否为空对象 (不含可枚举属性)。
- jQuery.isFunction():是否为函数
- jQuery.isNumberic():是否为数字
- jQuery.isPlainObject():是否为使用“{}”或“new Object”生成对象,而不是浏览器原生提供的对象。
- jQuery.isWindow(): 是否为window对象;
- jQuery.isXMLDoc(): 判断一个DOM节点是否处于XML文档中。
6、判断数组的另一种方法(推荐)
Array.isArray(arr)
总结
觉得写得好的,对你有帮助的,可以分享给身边人,知识越分享越多,千万不要吝啬呀
后续更新前端其它小知识总结,请关注我,整理好,分享给你们,我们一起学前端