jQuery是用toString来判断数据类型,而不是typeof或instanceof

// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number';// Despite being "Not-A-Number"
typeof Number(1) === 'number';// but never use this form!
 
// Strings
typeof "" === 'string';
typeof "bla" === 'string';
typeof (typeof1) === 'string';// typeof always return a string
typeof String("abc") === 'string';// but never use this form!
 
// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(true) === 'boolean';// but never use this form!
 
// Undefined
typeof undefined === 'undefined';
typeof blabla === 'undefined';// an undefined variable
 
// Objects
typeof {a:1} === 'object';
typeof [1, 2, 4] === 'object';// use Array.isArray or Object.prototype.toString.call to differentiate regular objects from arrays
typeof new Date() === 'object';
typeof null === 'object';
 
typeof new Boolean(true) === 'object';// this is confusing. Don't use!
typeof new Number(1) === 'object'; // this is confusing. Don't use!
typeof new String("abc") === 'object'; // this is confusing. Don't use!
 
// Functions
typeof function(){} === 'function';
typeof new Function() === 'function';
typeof Math.sin === 'function';
从上面的例子可知,typeof不能判断出数组和null,而且对于通过new操作符生成的对象,也无法判断类型。

至于instanceof,因为在JavaScript中,所有对象都是object,也就是说new Number(2)或new String('hello')也是object,故无法判断。

但Object.prototype.toString对任何变量会永远返回这样一个字符串"[object class]",而这个class就是JavaScript内嵌对象构造函数的名字。至于用户自定义的变量,则class等于object。因此通过Object.prototype.toString.apply(obj)可以准确的获取变量数据类型。通过Object.prototype.toString可以获得的数据类型包括:Date, Object, String, Number, Boolean, Regexp, Function, undefined, null, Math等。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值