In JavaScript, the data types that the typeof operator can return are: "undefined", "object", "boolean", "number", "string", "symbol", "function", etc.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Use the typeof
operator to return the data type of the variable.
Let’s take a look at the value of typeof corresponding to each data type:
Data type | Result |
---|---|
Undefined | "undefined" |
Null | "object" |
Boolean value | "boolean" |
numeric value | "number" |
Character String | "string" |
"symbol" | |
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';
Object.prototype.toString method to further judge the data type.
Let’s take a look at the difference between the return values of the toString method and the typeof method in the case of the same data type:toString | typeof | |
---|---|---|
String | string | |
String | object | |
Number | object | |
Boolean | boolean | |
Boolean | object | |
Date | object | |
Error | object | ##new Array(1, 2, 3) |
object | ##/abc/g | |
object | new RegExp(“meow”) | |
object | You can see that Array and Error can be correctly distinguished using the toString method , RegExp, Date and other types. |
[Related recommendations:
javascript learning tutorial]The above is the detailed content of What data types can JavaScript's typeof return?. For more information, please follow other related articles on the PHP Chinese website!