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

How does JavaScript determine the type? (code example)

青灯夜游
青灯夜游forward
2018-10-10 17:19:391901browse

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

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);

The output results are:

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

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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more