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