用js如何判断数据类型

常见的数据类型有:

根据js的数据类型,举几个例子:

var a;
var b=1;
var c="1";
var d=[1,2,3];
var e=function(){};

方法一:typeof来检查数据类型

typeof a -->undefined;

typeof b -->number;

typeof c -->string;

typeof d -->object;

typeof e -->function;

通过返回的布尔值来判断数据类型

typeof a =="undefined";  //true

typeof b =="number";  //true

typeof c =="string";  //true

typeof d =="object";  //true

typeof e =="function";  //true

方法二:instanceof来判断数据类型

 

a instanceof Undefined;  //true

b instanceof Number;  //true

c instanceof String;  //true

d instanceof Object;  //true

e instanceof Function;  //true

注意:instanceof后面一定要是对象类型,并且大小写不能错


方法三:constructor来判断数据类型

a.constructor==Undefined;  //true

b.constructor ==Number;  //true

c.constructor ==String;  //true

d.constructor==Array;  //true

e.constructor ==Function;  //true


方法四:prototype判断数据类型

Object.prototype.toString.call(a) === ‘[object Undefined]’);  // true;

Object.prototype.toString.call(b) === ‘[object Number]’);  // true;

Object.prototype.toString.call(c) === ‘[object String]’);  // true;

Object.prototype.toString.call(d) === ‘[object Array]’);  // true;

Object.prototype.toString.call(e) === ‘[object Function]’);  // true;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值