js判断数据类型的几种方法

本文介绍JavaScript中五种常用的数据类型判断方法:typeof、instanceof、constructor、对象原型和jquery.type(),并展示了每种方法的应用实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值