Using typeof in JavaScript to judge data types, you can only distinguish between basic types,
"Number", "string", "Undefined", "Boolean", "Object" five. For arrays, functions, and objects, their relationships are complex, using
TypeOf will return the "object" string uniformly.
It is not possible to distinguish between objects, arrays, and functions by simply using TypeOf. Or you might think of instanceof methods, such as the following:
var a = {};var b = [];var c = function () {};//a b C is an instance of Object Console.log (a instanceof object)//trueconsole.log (b ins Tanceof object)//trueconsole.log (c instanceof Object)//true//only array type B is an instance of array Console.log (a instanceof Array) Falseconsole.log (b instanceof Array)//trueconsole.log (c instanceof Array)//false//only the function type of C is the instance of function con Sole.log (a instanceof function)//falseconsole.log (b instanceof function)//falseconsole.log (c instanceof function)// True
Judging from the above code, to judge the composite data type, you can decide as follows:
Object (a Instanceof object) &&! (a instanceof Function) &&! (a instanceof function)//Array (a Instanceof object) && (a instanceof Array)//function (a instanceof Object) && (A In Stanceof Function)
A simpler way to use Object.prototype.toString.call () to determine the type, ECMA 5.1
The description of the method in [1] is this:
-
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, apply Object.prototype.toString.call () to all value types
The method results are as follows:
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.
Object.prototype.toString.call () Differentiating object types