Home  >  Article  >  Web Front-end  >  What are the methods to determine data type in js

What are the methods to determine data type in js

下次还敢
下次还敢Original
2024-05-01 09:57:171141browse

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.

What are the methods to determine data type in js

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

instanceofOperator 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

  • typeofOperator 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn