您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

javascript的typeof可返回哪些数据类型

2024/6/16 5:20:22发布39次查看
在javascript中,typeof操作符可返回的数据类型有:“undefined”、“object”、“boolean”、“number”、“string”、“symbol”、“function”等。
本教程操作环境:windows7系统、javascript1.8.5版、dell g3电脑。
使用 typeof 操作符可以返回变量的数据类型。
我们来看看各个数据类型对应typeof的值:
数据类型结果
undefined “undefined”
null “object”
布尔值 “boolean”
数值 “number”
字符串 “string”
symbol (ecmascript 6 新增) “symbol”
宿主对象(js环境提供的,比如浏览器) implementation-dependent
函数对象 “function”
任何其他对象 “object”
再看看具体的实例:
// numberstypeof 37 === 'number';typeof 3.14 === 'number';typeof math.ln2 === 'number';typeof infinity === 'number';typeof nan === 'number'; // 尽管nan是"not-a-number"的缩写,意思是"不是一个数字"typeof number(1) === 'number'; // 不要这样使用!// stringstypeof "" === 'string';typeof "bla" === 'string';typeof (typeof 1) === 'string'; // typeof返回的肯定是一个字符串typeof string("abc") === 'string'; // 不要这样使用!// booleanstypeof true === 'boolean';typeof false === 'boolean';typeof boolean(true) === 'boolean'; // 不要这样使用!// symbolstypeof symbol() === 'symbol';typeof symbol('foo') === 'symbol';typeof symbol.iterator === 'symbol';// undefinedtypeof undefined === 'undefined';typeof blabla === 'undefined'; // 一个未定义的变量,或者一个定义了却未赋初值的变量// objectstypeof {a:1} === 'object';// 使用array.isarray或者object.prototype.tostring.call方法可以从基本的对象中区分出数组类型typeof [1, 2, 4] === 'object';typeof new date() === 'object';// 下面的容易令人迷惑,不要这样使用!typeof new boolean(true) === 'object';typeof new number(1) ==== 'object';typeof new string("abc") === 'object';// 函数typeof function(){} === 'function';typeof math.sin === 'function';
我们会发现一个问题,就是typeof来判断数据类型其实并不准确。比如数组、正则、日期、对象的typeof返回值都是object,这就会造成一些误差。
所以在typeof判断类型的基础上,我们还需要利用object.prototype.tostring方法来进一步判断数据类型。
我们来看看在相同数据类型的情况下,tostring方法和typeof方法返回值的区别:
数据tostringtypeof
“foo” string string
new string(“foo”) string object
new number(1.2) number object
true boolean boolean
new boolean(true) boolean object
new date() date object
new error() error object
new array(1, 2, 3) array object
/abc/g regexp object
new regexp(“meow”) regexp object
可以看到利用tostring方法可以正确区分出array、error、regexp、date等类型。
所以我们一般通过该方法来进行数据类型的验证。
【相关推荐:javascript学习教程】
以上就是javascript的typeof可返回哪些数据类型的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product