In JavaScript, there are three ways to determine the data type: the typeof operator returns a string representing the data type of the variable. The instanceof operator checks whether an object belongs to a specific constructor. The Object.prototype.toString.call method returns a string representing the variable type, which is more accurate than typeof.
How to determine the data type in JavaScript
In JavaScript, determining the data type is a common task. The following introduces several common methods:
typeof operator
typeof
operator returns a string representing the data type of the variable. It is the simplest method, but it cannot differentiate between some similar data types.
Syntax:
<code>typeof variable;</code>
For example:
<code>console.log(typeof "Hello"); // "string" console.log(typeof 123); // "number" console.log(typeof true); // "boolean" console.log(typeof null); // "object" (错误地识别为对象)</code>
instanceof operator
instanceof
Operator checks for one Whether the object belongs to a specific constructor. It is useful for differentiating complex data types such as arrays, functions, and date objects.
Syntax:
<code>variable instanceof constructor;</code>
For example:
<code>console.log([] instanceof Array); // true console.log(function() {} instanceof Function); // true console.log(new Date() instanceof Date); // true</code>
Object.prototype.toString.call Method
Object.prototype The .toString.call
method returns a string representing the variable type. It is more accurate than the typeof
operator and can differentiate between arrays, functions and date objects.
Syntax:
<code>Object.prototype.toString.call(variable);</code>
For example:
<code>console.log(Object.prototype.toString.call([])); // "[object Array]" console.log(Object.prototype.toString.call(function() {})); // "[object Function]" console.log(Object.prototype.toString.call(new Date())); // "[object Date]"</code>
Notes
typeof
Operator would incorrectly identify null
as an object. The instanceof
operator cannot distinguish between native constructors and custom constructors. Object.prototype.toString.call
method can provide more accurate data type information, but its syntax is relatively complex. The above is the detailed content of What are the methods to determine data type in js. For more information, please follow other related articles on the PHP Chinese website!