您好,欢迎访问一九零五行业门户网

js中如何判断数据类型

方法一、js内置方法typeof
检测基本数据类型的最佳选择是使用typeof
typeof 来判断数据类型,只能区分基本类型,即 “number”,”string”,”undefined”,”boolean”,”object”,“function”,“symbol” (es6新增)七种。
对于数组、null、对象来说,其关系错综复杂,使用 typeof 都会统一返回 “object” 字符串。
示例:
var bool = truevar num = 1var str = 'abc'var und = undefinedvar nul = nullvar arr = [1,2,3]var obj = {}var fun = function(){}var reg = new regexp()console.log(typeof bool); //booleanconsole.log(typeof num); //numberconsole.log(typeof str); //stringconsole.log(typeof und); //undefinedconsole.log(typeof nul); //objectconsole.log(typeof arr); //objectconsole.log(typeof obj); //objectconsole.log(typeof reg); //objectconsole.log(typeof fun); //function
由结果可知,除了在检测null时返回 object 和检测function时放回function。对于引用类型返回均为object。
方法二、object.prototype.tostring()
object.prototype.tostring方法返回对象的类型字符串,因此可以用来判断一个值的类型。
var obj = {};obj.tostring() // "[object object]"上面代码调用空对象的tostring方法,结果返回一个字符串object object,其中第二个object表示该值的构造函数。这是一个十分有用的判断数据类型的方法。
object.prototype.tostring.call(value)
上面代码表示对value这个值调用object.prototype.tostring方法。
不同数据类型的object.prototype.tostring方法返回值如下。
数值:返回[object number]。字符串:返回[object string]。布尔值:返回[object boolean]。undefined:返回[object undefined]。null:返回[object null]。数组:返回[object array]。arguments 对象:返回[object arguments]。函数:返回[object function]。error 对象:返回[object error]。date 对象:返回[object date]。regexp 对象:返回[object regexp]。其他对象:返回[object object]。
那么利用这个特性,可以写出一个比typeof运算符更准确的类型判断函数。
封装出一个判断类型的函数如下:
var type = function (o){ var s = object.prototype.tostring.call(o); return s.match(/\[object (.*?)\]/)[1].tolowercase();};type({}); // "object"type([]); // "array"type(5); // "number"type(null); // "null"type(); // "undefined"type(/abcd/); // "regex"type(new date()); // "date"
另外:还可以加上专门判断某种类型数据的方法
var type = function (o){ var s = object.prototype.tostring.call(o); return s.match(/\[object (.*?)\]/)[1].tolowercase();};var arr = ['null', 'undefined', 'object', 'array', 'string', 'number', 'boolean', 'function', 'regexp']arr.foreach(function (t) { type['is' + t] = function (o) { return type(o) === t.tolowercase(); };});
之后我们可以通过封装出的方法去在不同需求时使用:如下
type.isobject({}) // truetype.isnumber(nan) // truetype.isregexp(/abc/) // true
推荐教程:js入门教程
以上就是js中如何判断数据类型的详细内容。
其它类似信息

推荐信息