欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

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

来源: javaer 分享于  点击 2578 次 点评:177

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


// 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等。



相关文章

    暂无相关文章

用户点评