在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”再看看具体的实例
// numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof math.ln2 === 'number';
typeof infinity === 'number';
typeof nan === 'number'; // 尽管nan是not-a-number的缩写,意思是不是一个数字
typeof number(1) === 'number'; // 不要这样使用!// strings
typeof === 'string';
typeof bla === 'string';
typeof (typeof 1) === 'string'; // typeof返回的肯定是一个字符串
typeof string(abc) === 'string'; // 不要这样使用!// booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof boolean(true) === 'boolean'; // 不要这样使用!// symbols
typeof symbol() === 'symbol';
typeof symbol('foo') === 'symbol';
typeof symbol.iterator === 'symbol';// undefined
typeof undefined === 'undefined';
typeof blabla === 'undefined'; // 一个未定义的变量,或者一个定义了却未赋初值的变量// objects
typeof {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学习教程】