Native JS provides the typeof operator to judge the type, but it is not a problem when judging the basic type, but it is somewhat unsatisfactory when judging the complex type.
What are the basic types?
The argument is that null and function are not basic types? Individuals who feel that they can be typeof out of the right type are the basic types and look at the following code:
/*Basic Type*/Alert (typeofnudefined);//output "nudefined"Alerttypeof function(){});//output "function"Alerttypeof"A");//output "string"Alerttypeof1);//output "number"Alerttypeof true);//Output "Boolean"/*Complex Types*/Alert (typeof[]);//output "Object"Alerttypeof{});//output "Object"Alerttypeof NewDate ());//output "Object"Alerttypeof NewREGEXP ());//output "Object"Alerttypeof NULL);//output "Object"
The above using typeof can correctly output the basic type value, and the complex type output is "Object", then how to correctly know the correct type of complex type value?
Object.prototype.toString.call () Look at the description in ECMA5:
- When the ToString method was called, the following steps is taken:
- If The This value is undefined, return "[Object undefined]".
- If The This value is NULL, return "[Object null]".
Let O is the
- result of calling Toobject passing
the This value as the argument. Let class is the value of the
- [[class]] internal property of O.
- Return The String value that is the result of concatenating the three Strings "[Object", Class, and "]".
Since everything in JavaScript is an object, no exception, applying the Object.prototype.toString.call () method to all value types results in the following:
(Small knowledge Point: Why the JS in everything is the object, because you put any type as object when it is the object, the background will automatically wrap it into objects)
Console.log (Object.prototype.toString.call (123))//[Object number]Console.log (Object.prototype.toString.call (' 123 '))//[Object String]Console.log (Object.prototype.toString.call (undefined))//[Object Undefined]Console.log (Object.prototype.toString.call (true))//[Object Boolean]Console.log (Object.prototype.toString.call ({}))//[Object Object]Console.log (Object.prototype.toString.call ([]))//[Object Array]Console.log (Object.prototype.toString.call (function(){}))//[Object Function]
All types will get different strings, almost perfect. Really perfect.
Object.prototype.toString.call () can be simplified into {}.tostring.call ().
"JavaScript experience" JavaScript type judgment