如何判断JavaScript数据具体类型

昨晚做了阿里的题目,让我写一个函数,可以判断数据的具体类型。其实题目很简单的。。。但是真的是自己不太注意吧,写的很糟糕啊。

然后今天就自己写了一个,然后又到晚上搜了下,看看别人的写法,结果发现自己有点思维受限啊,不够开阔啊,那些方法其实都是见过的,可能是自己没有梳理过,或者认真对待。今天就把这些方法整理一下。

 

1、基本数据类型采用typeof,这个返回的都是很准的。

var a = "iamstring.";
var b = 222var c= [1,2,3];
var e = function(){alert(111);};
var f = function(){this.name="22";};

alert(typeof a)   ------------> string
alert(typeof b)   ------------> number
alert(typeof c)   ------------> object//数组是引用类型的
alert(typeof f)   ------------> function
alert(typeof e)   ------------> function

 

2、引用类型采用instanceof,主要针对的是采用new 实例化的对象。

var a = new String("iamstring.");
var b = new Number(222var c = new Array(222,4function(){console.log(111;};
var h = new Error("foo");

console.log(a instanceof String)    true  
console.log(b instanceof Number)    true  
console.log(c instanceof Array)     true  
console.log(e instanceof Function)  true   
console.log(f true  
console.log(h instanceof Error)     true  

 

3、根据constructor来判断

其中a-h跟上面的一样,就不重复定义了,注意不带引号的,是要大写

var i="str",arr=[1],num=1;
console.log(a.constructor=== String)    true  
console.log(b.constructor=== Number)    true  
console.log(c.constructor=== Array)     true  
console.log(e.constructor=== Function)  true   
console.log(f.constructor=== Function)  true  
console.log(h.constructor===Error)      true 
console.log(i.constructor===String)     true 
console.log(num.constructor=== Number)    true  
console.log(arr.constructor=== Array)     true 

 

4、toString()方法,这是最通用的,大小写不能写错,有点麻烦

console.log(Object.prototype.toString.call(a) === ‘[object String]’) -------> true;

console.log(Object.prototype.toString.call(b) === ‘[object Number]’) -------> ;

console.log(Object.prototype.toString.call(c) === ‘[object Array]’) -------> ;

console.log(Object.prototype.toString.call(d) === ‘[object Date]’) -------> ;

console.log(Object.prototype.toString.call(e) === ‘[object Function]’) -------> ;

console.log(Object.prototype.toString.call(f) === ‘[object Function]’) -------> true;

 

5、可以采用一些某些数据类型采用的方法

比如:string 类型的 replace

regexp类型的test,exec

数组还有一种判断方法:Array.isArray()

date 类型的 getMonth()等

 

相关文章

kindeditor4.x代码高亮功能默认使用的是prettify插件,prett...
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小