In JavaScript, typeof is used to determine the data type. Only the basic types can be distinguished, namely, "number", "string", "undefined", "boolean", and "object. For arrays, functions, and objects, the relationship is complex. If typeof is used, the "object" string is returned in a unified manner.
To distinguish objects, arrays, and functions, simply using typeof is not acceptable. Or you will think of the instanceof method, such as the following:
Var a = {}; var B = []; var c = function () {}; // a B c is the console of the Object instance. log (a instanceof Object) // trueconsole. log (B instanceof Object) // trueconsole. log (c instanceof Object) // true // only Array type B is the instance console of Array. log (a instanceof Array) // falseconsole. log (B instanceof Array) // trueconsole. log (c instanceof Array) // false // only Function-type c is the Function instance console. log (a instanceof Function) // falseconsole. log (B instanceof Function) // falseconsole. log (c instanceof Function) // true
From the code above, you can judge the composite data type as follows:
// Object (a instanceof Object )&&! (A instanceof Function )&&! (A instanceof Function) // Array (a instanceof Object) & (a instanceof Array) // Function (a instanceof Object) & (a instanceof Function)
The simpler way is to use Object. prototype. toString. call () to determine the type. The description of this method in ECMA 5.1 [1] is as follows:
-
When the toString method is called, the following steps are taken:
-
If the this value is undefined, return "[object Undefined]".
-
If the this value is null, return "[object Null]".
-
Let O be the result of calling ToObject passing the this value as the argument.
-
Let class be 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 "]".
Because everything in JavaScript is an Object, nothing is an exception, the results of applying the Object. prototype. toString. call () method to all value types 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.
[1] Object. prototype. toString ()