本文摘自PHP中文网,作者V,侵删。
方法一、js内置方法typeof
检测基本数据类型的最佳选择是使用typeof
typeof 来判断数据类型,只能区分基本类型,即 “number”,”string”,”undefined”,”boolean”,”object”,“function”,“symbol” (ES6新增)七种。
对于数组、null、对象来说,其关系错综复杂,使用 typeof 都会统一返回 “object” 字符串。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | var bool = true
var num = 1
var str = 'abc'
var und = undefined
var nul = null
var arr = [1,2,3]
var obj = {}
var fun = function (){}
var reg = new RegExp()
console.log( typeof bool);
console.log( typeof num);
console.log( typeof str);
console.log( typeof und);
console.log( typeof nul);
console.log( typeof arr);
console.log( typeof obj);
console.log( typeof reg);
console.log( typeof fun);
|
由结果可知,除了在检测null时返回 object 和检测function时放回function。对于引用类型返回均为object。
方法二、Object.prototype.toString()
Object.prototype.toString方法返回对象的类型字符串,因此可以用来判断一个值的类型。
1 2 | var obj = {};
obj.toString()
|
Object.prototype.toString.call(value)
上面代码表示对value这个值调用Object.prototype.toString方法。
不同数据类型的Object.prototype.toString方法返回值如下。
1 2 3 4 5 6 7 8 9 10 11 12 | 数值:返回[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运算符更准确的类型判断函数。
封装出一个判断类型的函数如下:
1 2 3 4 5 6 7 8 9 10 11 | var type = function (o){
var s = Object.prototype.toString.call(o);
return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};
type({});
type([]);
type(5);
type( null );
type();
type(/abcd/);
type( new Date());
|
另外:还可以加上专门判断某种类型数据的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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();
};
});
|
之后我们可以通过封装出的方法去在不同需求时使用:如下
1 2 3 | type.isObject({})
type.isNumber(NaN)
type.isRegExp(/abc/)
|
推荐教程:js入门教程
以上就是js中如何判断数据类型的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
如何使用js实现简单日历效果
js获取dom元素的方式总结
js 中排名前十的报错如何避免
js如何判断一个对象是否是数组(函数)
js数组的函数用法详解
js怎么判断是否为数字
js中数组的迭代方法:filter、reduce、every、some
js如何实现利用键盘控制div移动
js屏蔽pc端访问
如何利用js获取form表单数据
更多相关阅读请进入《js》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » js中如何判断数据类型