Typeof determined using the JavaScript data type, can distinguish only basic types, namely: number, string, undefined, boolean , object, function.
For null, array, object, using typeof unity will return a string object.
To distinguish objects, arrays, functions, simple to use typeof is not enough. In JS, by Object.prototype.toString method, which determines the type of an object built belongs.
Built-in types are divided into null, string, boolean, number, undefined, array, function, object, date, math.
- 判断基本类型
1 Object.prototype.toString.call(null); // “[object Null]”
2 Object.prototype.toString.call(undefined); // “[object Undefined]”
3 Object.prototype.toString.call(“abc”);// “[object String]”
4 Object.prototype.toString.call(123);// “[object Number]”
5 Object.prototype.toString.call(true);// “[object Boolean]” - Analyzing primary reference type
1 function type
. Function fn(){ console.log(“test”); }
Object.prototype.toString.call(fn); // “[object Function]”
Date Type 2
var date = new Date();
. Object.prototype.toString.call(date); // “[object Date]”
3 array type
. var arr = [1,2,3];
Object.prototype.toString.call(arr); // “[object Array]”
4 Regular Expressions
. var reg = /[hbc]at/gi;
. Object.prototype.toString.call(reg); //"[object RegExp]"
Custom Type 5
. function Person(name, age) {
this.name = name;
this.age = age; }
var person = new Person("Rose", 18);
Object.prototype.toString.call(arr); // "[object Object]"
Clearly this method can not accurately determine the person is an instance of the Person class, but can only use the instanceof operator to judge, as follows:
the console.log (instanceof Person person); // to true
Native JSON object 5 is determined
. Var isNativeJSON = window.JSON &&
Object.prototype.toString.call (JSON); the console.log (isNativeJSON); //
output is "[object JSON]" Description JSON is native, or not;
Note: Object. prototype.toString () itself is allowed to be modified, and on Object.prototype.toString () method is applied this hypothesis toString () method we have discussed so far has not been modified as a precondition.