There are several common data types in JavaScript:

Basic types: string, number, Boolean, Symbol

Special type: undefined, null

Reference types: Object, Function, Function, Array, Date…


1, the typeof

typeof ' ';               / / string is effective
typeof 1;                / / number is effective
typeof true;             / / a Boolean is effective
typeof undefined;        / / undefined effectively
typeof null;             / / object is invalid
typeof[];/ / object is invalid
typeof new Function(a);/ / function effectively
typeof new Date(a);/ / object is invalid
typeof new RegExp(a);/ / object is invalid
Copy the code

In JavaScript, typeof is used to determine data types. Only basic types can be distinguished, namely “number”, “string”, “undefined”, “Boolean”, and “object”.

The relationship between arrays, functions, and objects is complex, and typeof returns “object” strings uniformly.

So, want to distinguish objects, arrays, functions, use typeof is no good, pure JavaScript, through the Object. The prototype. The toString method to determine an Object value belong to which kinds of built-in types.


2, the Object. The prototype. ToString and $. The type ()

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]
console.log(Object.prototype.toString.call(this));        // [object Window]
Copy the code

Check whether it is a function:

function isFunction(it) {
    return Object.prototype.toString.call(it) === '[object Function]';
}
Copy the code

Check whether it is an array:

function isArray(o) { 
    return Object.prototype.toString.call(o) === '[object Array]';  
}
Copy the code

Here have to say the Object. The prototype. ToString. Call () is really judge data type “essential oils” * * * *! (The trick doesn’t have to be last /doge/)

In the Object. The prototype. The toString method is called, will perform the following steps (understand) :

  1. Gets the value of the [[Class]] property of this.

  2. Evaluates the three strings “[object “, the Result of the first step, Result(1), and the new string concatenated by “]”.

  3. Returns Result(2) of the second step.

[[Class]] is an internal property that all objects (native and host) have. In the specification, [[Class]] is defined as:

Internal properties describe
[[Class]] A string value indicating the type of the object.

Important: [[Class]] indicates the type of the object

Now that you know how to accurately judge data types, you feel better about yourself.

Maybe you used jQuery $. The type () method to determine the data type, it is the Object. The prototype. The toString. Call a wrapper (), and in the vue – in the place such as the source of the router is used to transform and testing data types.


Data types, of course, beyond the above three methods (typeof, Object. The prototype. ToString, $. The type ()), data type and instanceof and constructor judgment, but they have some disadvantages.

3, instanceof

console.log(2 instanceof Number);                    // false
console.log(true instanceof Boolean);                // false 
console.log('str' instanceof String);                // false  
console.log([] instanceof Array);                    // true
console.log(function(){} instanceof Function);       // true
console.log({} instanceof Object);                   // true

// These two are special, explain a little
// console.log(undefined instanceof Undefined);
// console.log(null instanceof Null);
Copy the code

As shown in the above results, only reference data types (Array, Function, Object) are evaluated accurately. Other literals (Number, Boolean, String) are not evaluated accurately by instanceof.

The instanceof operator tests whether an object has the prototype property of a constructor in its prototype chain. This means determining whether an object is an instance of a data type (such as Array). Focus on determining whether an object is an instance of a data type. Here the literal value, 2, true, ‘STR’ is not an instance, so the value is judged to be false. Seeing is believing. Here’s an example:

console.log(new Number(2) instanceof Number)      // true
console.log(new Boolean(true) instanceof Boolean) // true
console.log(new String('str') instanceof String)  // true
Copy the code

Literals are instantiated and their judgment value becomes true.

Let’s take a look at undefined and NULL and explain why they are special. In fact, null is supposed to belong to the same class as NULL and undefined is supposed to belong to the same class as undefined, but that’s not the case. The console output is as follows:

console.log(new undefined instanceof Undefined)
// TypeError: undefined is not a constructor
console.log(new null instanceof Null)
// TypeError: null is not a constructor
Copy the code

Browsers consider null, undefined is not a constructor. The result of typeof null is object, and the result of typeof undefined is undefined. This is a big mistake for JavaScript designers. Dart, Google’s alternative to JavaScript, explicitly states that null is not undefined.

Want to know the difference between undefined and null May have a look Nguyen other great god blog: www.ruanyifeng.com/blog/2014/0…


4, the constructor

console.log((2).constructor === Number);                // true
console.log((true).constructor === Boolean);            // true
console.log(('str').constructor === String);            // true
console.log(([]).constructor === Array);                // true
console.log((function() {}).constructor === Function);  // true
console.log(({}).constructor === Object);               // true
Copy the code

Using Costructor to determine type may seem perfect, but if I create an object and change its prototype, it becomes unreliable.

function Fn(){};
 
Fn.prototype = new Array(a);var f = new Fn();
console.log(f.constructor === Fn);    // false
console.log(f.constructor === Array); // true

Copy the code

So easily changed its constructor, shows what the Object. The prototype. The toString, call () really sweet, / doge.

The above is my JavaScript data type judgment of a learning summary, we come on!

Ps: If you have a pit in Guangzhou, please contact me at [email protected].