Home > Web Front-end > JS Tutorial > How does JavaScript determine the type? (code example)

How does JavaScript determine the type? (code example)

青灯夜游
Release: 2018-10-10 17:19:38
forward
1934 people have browsed it

This article will introduce to you how to determine the type in JavaScript? (Code example) has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The typeof method in JS can check the type of data, as follows:

console.log(typeof 2); // number
console.log(typeof "2"); // string
console.log(typeof true); // boolean
console.log(typeof [2]); // object
console.log(typeof {name:2});// object
console.log(typeof function(){return 2});// function
console.log(typeof new Date());// object
console.log(typeof null); // object
console.log(typeof undefined);// undefined
Copy after login

But typeof can only distinguish between numbers, strings, Boolean values, methods and undefined, other objects, arrays, dates, null, etc. are all objects, but they still cannot be distinguished.

We can use Object.prototype.toString.call to achieve this.

 var getType = Object.prototype.toString;
var res = getType.call(2);
res = getType.call("2");
res = getType.call(true);
res = getType.call([2]);
res = getType.call({name:2});
res = getType.call(function(){});
res = getType.call(new Date());
res = getType.call(null);
res = getType.call(undefined);
Copy after login

The output results are:

[object Number]
[object String]
[object Boolean]
[object Array]
[object Object]
[object Function]
[object Date]
[object Null]
[object Undefined]
Copy after login

This way, the data types in JS can be specifically distinguished.

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. For more related tutorials, please visit JavaScript Video Tutorial!

Related recommendations:

php public welfare training video tutorial

JavaScript graphic tutorial

JavaScriptOnline Manual

The above is the detailed content of How does JavaScript determine the type? (code example). 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