Front-end partners all know js as a basic skill, which is essential is the JS data type, which is also our advanced middle and advanced front-end familiar with the internal skill training in the heart…

I will help you sort out and deeply study the knowledge points of JavaScript data types from the concepts of data types, detection methods and conversion methods.

Data type concept

There are eight types of JavaScript data as shown below:

Of these, the first seven are base types, and the last (Object) is the reference type, which you should focus on because it is the most frequently used data type in your daily work and requires the most technical attention

The biggest difference between the js base data type and the reference data type is where the data structure is stored:

1. Base types are stored in stack memory, and when referenced or copied, an exact equal variable is created;

2. Reference types are stored in heap memory and store addresses. Multiple references refer to the same address.

let a = { name: 'lee', age: 18 } let b = a; console.log(a.name); //lee b.name = 'son'; console.log(a.name); //son console.log(b.name); //son let a = { name: 'Julia', age: 20 } function change(o) { o.age = 24; o = { name: 'Kath', age: 30 } return o; } let b = change(a); console.log(b.age); // 30 console.log(a.age); / / 24Copy the code

Data type detection

The first judgment method: Typeof

typeof 1 // 'number'

typeof '1' // 'string'

typeof undefined // 'undefined'

typeof true // 'boolean'

typeof Symbol() // 'symbol'

typeof null // 'object'

typeof [] // 'object'

typeof {} // 'object'

typeof console // 'object'

typeof console.log // 'function'
Copy the code

As you can see, the first six are basic datatypes, but why is the sixth null typeof ‘object’? Note that typeof NULL outputs object, but this is a long-standing JS Bug. Null does not refer to data types, and null itself is not an object. Therefore, NULL returns problematic results after typeof and cannot be used as a method to determine null. If you need to check for null in an if statement, just say ‘===null’.

Note that if you refer to a datatype (Object), you can use typeof (function) as’ Object ‘and (function) as’ Object’.

The second judgment method: instanceof

The instanceof operator is used to check whether the constructor’s prototype property appears on the prototype chain of an instance object.

The instanceof operator is used to test whether constructor. Prototype exists on the prototype chain of the parameter Object.

let Car = function() {}

let benz = new Car()

benz instanceof Car // true

let car = new String('Mercedes Benz')

car instanceof String // true

let str = 'Covid-19'

str instanceof String // false
Copy the code

The above is the general flow of using instanceof to determine the data type, so if you have to implement a low-level implementation of Instanceof, what should you write? Look at the code below.

The object.getProtoTypeof () method returns the Prototype of the specified Object (the value of the internal [[Prototype]] property). Function myInstanceof(left, right) {// Return false if(typeof left! == 'object' || left === null) return false; Let proto = object.getProtoTypeof (left); If (proto === null) return false; if(proto == null) return false; if(proto === right.prototype) return true; // Find the same prototype object, return true}} console.log(myInstanceof(new Number(123), Number)); // true console.log(myInstanceof(123, Number)); // falsettyCopy the code

Both Typeof and Instanceof can determine data types, but both have advantages and disadvantages:

  1. Instanceof can accurately determine complex reference data types, but not the underlying data types.

  2. Typeof also suffers from the fact that while it can determine the underlying data type (except null), it cannot determine any reference data type other than the function type.

In short, typeof and Instanceof alone are not sufficient for all scenarios, and can only be judged by mixing them. But this way of judging is actually only the majority of cases, and it is also uncomfortable to write, you can also try to write.

In fact, I personally prefer the third method below, which can solve the data type detection problem better than the above two

The third judgment method: Object. The prototype. ToString

ToString () is an Object prototype method that returns uniformly a string of the format “[Object Xxx]”, where Xxx is the type of the Object. For Object objects, toString() returns [Object Object]; Other objects need to be called by call to return the correct type information. Let’s look at the code.

Object. The prototype. ToString ({}) / / "[Object Object]" Object. The prototype. ToString. Call ({}) / / same as above result, Plus the call also ok Object. The prototype. ToString. Call (1) / / "[Object Number]" Object. The prototype. ToString. Call (' 1 ') / / "[Object String]" Object.prototype.toString.call(true) // "[object Boolean]" Object.prototype.toString.call(function(){}) // "[object Function]" Object.prototype.toString.call(null) //"[object Null]" Object.prototype.toString.call(undefined) //"[object Undefined]" Object.prototype.toString.call(/123/g) //"[object RegExp]" Object.prototype.toString.call(new Date()) //"[object Date]" Object.prototype.toString.call([]) //"[object Array]" Object.prototype.toString.call(document)  //"[object HTMLDocument]" Object.prototype.toString.call(window) //"[object Window]"Copy the code

This code can be seen from the above Object. The prototype. ToString. The call () is a good way to judge a reference type, it can even make a distinction between the document and the window.

Note that this method returns “[object Xxx]”, and the first letter of “Xxx” in the string must be capitalized (note: typeof returns lowercase).

So let’s implement a global general datatype determination method to deepen your understanding, the code is as follows.

function getType(obj){ let type = typeof obj; if (type ! == "object") {// Return type; } // If typeof returns object, Regular returns the return Object. The prototype. ToString. Call (obj). Replace (/ ^ \ [Object (\ S +) \] $/, "$1"); } /* Regex () {// Regex () {// regex () {// regex () {// regex () {// */ getType([]) // "Array" typeof [] is object, ToString returns getType('123') // "string" typeOF directly returns getType(window) // "window" toString returns getType(null) // "null" uppercase letter, Typeof NULL is object, GetType (undefined) // "undefined" typeof returns getType() // "undefined" typeof returns getType(function(){}) // "Function" typeof can judge, so lowercase getType(/123/g) //"RegExp" toString returns z summaryCopy the code

conclusion

From the above three methods, the first two methods have their disadvantages, can not adapt to the development needs of the real scene, the third method

Object. The prototype. ToString. Call by calling the toString method to return the data on the prototype chain type, can apply to the front-end development demand of any scene.

Note: refer to the core principles of JavaScript series