在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”stringstringnew string(“foo”)stringobjectnew number(1.2)numberobjecttruebooleanbooleannew boolean(true)booleanobjectnew date()dateobjectnew error()errorobjectnew array(1, 2, 3)arrayobject/abc/gregexpobjectnew regexp(“meow”)regexpobject
可以看到利用tostring方法可以正确区分出array、error、regexp、date等类型。
所以我们一般通过该方法来进行数据类型的验证。
【相关推荐:javascript学习教程】
云服务器用什么运行代码腾讯云服务器公有与私有的区别企业注册国外域名是何原因?有什么特别意义?辰海集团与华为云签署全面合作协议,共同服务出海企业,助力中国品牌走向世界网站优化做好应该拥有哪些思维如何刺激用户参与活动,不妨和网易严选APP学讲故事云开发和云服务器的区别在哪金匙医学完成2.3亿元C轮融资 品牌域名能否成为金钥匙?