js判断数据类型的几种方法
2017-10-24 14:23
696 查看
var a="zjj"; var b=523; var c=[1,2,3]; var d=new Date(); var e=false; var f=new Boolean(true); var g=function(){ console.log(123); }; var h=NaN; var i=undefined; var j=null;
1.最常用的typeof
typeof在判断除Object类型的对象时比较方便
typeof返回的类型都是字符串形式,能判断的类型有number,string,object,function,undefiend
console.log(typeof a); //string console.log(typeof b); //number console.log(typeof c); //object console.log(typeof d); //object console.log(typeof e); //boolean console.log(typeof f); //object console.log(typeof g); //function console.log(typeof h); //number console.log(typeof i);//undefined console.log(typeof j);//object
[b]2.instanceof判断已知对象的引用类型
[/b]
如果已经知道一个数据是对象类型,那么可以用instanceof来判断它是Array,Date,Function,String,Number,Object。
instanceof不能判断null和undefined.
console.log(c instanceof Array); //true console.log(d instanceof Date); //true console.log(e instanceof Boolean); //false console.log(f instanceof Boolean); //true console.log(g instanceof Function); //true
3.根据对象的constructor的判断
construstor能判断number,string,boolean,array,object,date,function,不能判断null和undefined
console.log(c.constructor===Array);//true console.log(d.constructor===Date);//true console.log(e.constructor===Boolean);//true console.log(f.constructor===Boolean);//true console.log(g.constructor===Function);//true console.log(h.constructor===Number);//true4.根据对象的原型prototype判断,能判断所有类型
console.log(Object.prototype.toString.call(a));//[object String] 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 Boolean] console.log(Object.prototype.toString.call(f));//[object Boolean] console.log(Object.prototype.toString.call(g));//[object Function] console.log(Object.prototype.toString.call(h));//[object Number] console.log(Object.prototype.toString.call(i));//[object Undefined] console.log(Object.prototype.toString.call(j));//[object Null]5.jquery.type()方法能判断所有类型
console.log($.type(a));//string console.log($.type(b));//number console.log($.type(c));//array console.log($.type(d));//date console.log($.type(e));//boolean console.log($.type(f));//boolean console.log($.type(g));//function console.log($.type(h));//number console.log($.type(i));//undefined console.log($.type(j));//null
相关文章推荐
- 判断js中的数据类型的几种方法
- JS中判断数据类型的几种方法
- 转:判断js中的数据类型的几种方法
- 判断js中的数据类型的几种方法
- 判断js中的数据类型的几种方法
- 判断JS数据类型的几种方法
- 粗体判断js中的数据类型有一下几种方法
- Js中数据类型判断的几种方法
- js 判断数据类型的几种方法
- js 判断数据类型的几种方法
- 判断js中的数据类型的几种方法
- js中判断数据类型对的几种方法
- js 判断数据类型的几种方法
- 判断js中的数据类型的几种方法
- js判断数据类型的几种方法及应用场景分析
- 判断js中各种数据的类型方法之typeof与0bject.prototype.toString讲解
- js 判断各种数据类型的简单方法(推荐)
- js数据类型的判断方法
- flex 判断数据类型的几种方法
- JS小技巧:判断数据类型的一种方法