Home > Article > Web Front-end > In-depth understanding of the difference between typeof and instanceof in JavaScript
This time I mainly talk about the usage and precautions of JavaScript's type judgment function typeof and judgment constructor prototype instanceof.
Let’s talk about typeof first. The first thing to note is that the typeof method returns a string to represent the type of the data.
Let’s first look at the value of typeof corresponding to each data type:
Data type | Type |
---|---|
Undefined | “undefined” |
Null | "object" |
Boolean value | "boolean" |
numeric value | "number " |
string | "string" |
Symbol (new in ECMAScript 6) | " symbol” |
Host object (provided by the JS environment, such as the browser) | Implementation-dependent |
Function object | "function" |
Any other object | "object" |
Look again Specific example:
// 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';
We will find a problem, that is, typeof is not accurate to determine the data type. For example, the typeof return value of arrays, regular expressions, dates, and objects is all object, which will cause some errors.
So on the basis of typeof judging the type, we also need to use the 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:
Data | toString | typeof |
---|---|---|
"foo" | String | string |
new String(“foo”) | String | object |
Number | object | |
Boolean | boolean | |
Boolean | object | |
Date | object | |
Error | object | |
Array | object | ##/abc/g |
object | new RegExp(“meow”) | |
object |
The above is the detailed content of In-depth understanding of the difference between typeof and instanceof in JavaScript. For more information, please follow other related articles on the PHP Chinese website!