js判斷數據類型的幾種方法

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

2.instanceof判斷已知對象的引用類型

如果已經知道一個數據是對象類型,那麼可以用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);//true
4.根據對象的原型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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章