判断数据类型的几种方法
参考链接1
参考链接2
1.typeof
用typeof判断数据类型,大家应该都知道了,我在前面的文章也有提过typeof可以判断的数据类型。
typeof可以返回所有的值类型,
可以判断是否为引用类型,但是无法具体判断出属于哪种引用类型,因为所有的返回值都为‘Object’
2.instanceof
instanceof 返回布尔值
我原以为利用instanceof可以判断出引用类型,但是instanceof是基于原型和原型链的,如果修改了他的原型就无法判断。
缺点:只能判断对象是否存在于目标对象的原型链上,不能判断基本数据类型
在此感谢面试官小哥哥,又学到了!
3.通过Object下的toString.call()方法来判断
Object.prototype.toString.call();
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]
4.根据对象的contructor判断
var a = 1;
var b = new Number(1);
function func() {
console.log("haha");
}
func.prototype = new Array();
var func2 = new func();
var date = new Date();
var arr = [1, 2, 3];
console.log('数据类型判断', constructor);
console.log(arr.constructor === Array); //true
console.log(date.constructor === Date); //true
console.log(func.constructor === Function); //true
// 注不能用于undefined 与 null 因为它们没有构造函数
5.jq中判断数据类型的方法
jQuery提供了一系列工具方法,用来判断数据类型,以弥补JavaScript原生的typeof运算符的不足。以下方法对参数进行判断,返回一个布尔值。
jQuery.isArray();是否为数组
jQuery.isEmptyObject();是否为空对象 (不含可枚举属性)。
jQuery.isFunction();是否为函数
jQuery.isNumberic();是否为数字
jQuery.isPlainObject();是否为使用“{}”或“new Object”生成对象,而不是浏览器原生提供的对象。
jQuery.isWindow(); 是否为window对象;
jQuery.isXMLDoc(); 判断一个DOM节点是否处于XML文档中。