前一阵写过一个如何判断数据类型的文章,再更新一些。
在 JavaScript 里使用 typeof 来判断数据类型,只能区分基本类型,即 “number”,”string”,”undefined”,”boolean”,”object” 五种。对于数组、函数、对象来说,其关系错综复杂,使用
typeof 都会统一返回 “object” 字符串。
还可以使用instanceof,例如
var arr = [];
if(arr instanceof Array){
console.log(1);
}
这个之前写过了,其实和constructor意思是一样的,MDN上查到的资料是All objects will have a constructor
property.
Objects created without the explicit use of a constructor function (i.e. the object and array literals) will have a constructor
property
that points to the Fundamenal Object constructor type for that object.
可以通过arr.constructor == Array来判断。
具体的constructor是什么意思,JS高程上有解释,以后有时间再研究。
还要一个最通用的是
Object.prototype.toString.call(value)
该方法返回的是一个字符串,比如下面的代码:
函数类型
Function fn(){console.log(“test”);}
Object.prototype.toString.call(fn);//”[object Function]”
日期类型
var date = new Date();
Object.prototype.toString.call(date);//”[object Date]”
数组类型
var arr = [1,2,3];
Object.prototype.toString.call(arr);//”[object Array]”
正则表达式
var reg = /[hbc]at/gi;
Object.prototype.toString.call(reg);//”[object RegExp]”
但是自定义类型无法识别