In the actual project development, may often encounter data type of judgment, I also often go to degree niang, not carefully summed up, recently idle down to do a summary bar.
The basic data types of JavaScript are: Undefined, Null, Boolean, number, String. There is also a reference data type object, and on the basis of object to inherit more types, such as array,date,function, of course, including our own created constructors;
That how more rigorous to judge the type of data, in the development of the more important, the degree Niang saw a lot of methods, it boils down to three kinds:
1. Constructor (constructor)
The constructor property returns a reference to the array function that created this object, (A.constructor = = array)//A constructor for the instance is an array? True or False
Console.log ([].constructor = = Array); Console.log ({}.constructor = = Object); Console.log ("string". Constructor = = String); Console.log ((123). constructor = = number); Console.log (true.constructor = = Boolean);
2. instanceof (example)
instance, hence the name of righteousness, examples, examples, so instanceof used to judge whether a variable is an instance of an object
var a=[];console.log (a instanceof Array)//return True
3. toString
This method is more complex, do not do too much explanation, the following:
var arr = [];object.prototype.tostring.call (arr) = = ' [Object Array] ';
The method is more rigorous, and the corresponding other types of data are judged as: [Object object],[object String],[object number],[object Boolean]
Refer to the experience of other bloggers and some personal summary, if there is infringement, please contact me in time, qq:435641688, thank you
Method of JS Judging type