Home > Web Front-end > JS Tutorial > How to accurately determine the data type of a variable in js

How to accurately determine the data type of a variable in js

王林
Release: 2020-07-11 17:05:03
forward
2894 people have browsed it

How to accurately determine the data type of a variable in js

can be achieved through the toString() method.

(Recommended tutorial: js tutorial)

Function introduction:

toString() is the prototype method of Object. When this method is called, the current value is returned by default [[Class]] of the object. This is an internal property with the format [object Xxx] , where Xxx is the type of object.

For Object objects, calling toString() directly will return [object Object]. For other objects, you need to call / apply to return the correct type information.

Function syntax:

number.toString(radix)
Copy after login

Code example:

Object.prototype.toString.call('') ;   // [object String]
Object.prototype.toString.call(1) ;    // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(Symbol()); //[object Symbol]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
Object.prototype.toString.call(new Error()) ; // [object Error]
Object.prototype.toString.call(document) ; // [object HTMLDocument]
Object.prototype.toString.call(window) ; //[object global] window 是全局对象 global 的引用
Copy after login

The above is the detailed content of How to accurately determine the data type of a variable in js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template