Make writing a habit together! This is the fourth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

preface

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:

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

There are also several reference types: array-array objects, regexp-regular objects, date-date objects, math-math functions, and function-function objects.

Storage difference between base type and reference type:

  1. Base type: stored in stack memory, referenced or copied, creates an exact equal variable;
  2. Reference type: Stored in heap memory, the storage is the address, multiple references to the same address, there will be a “shared” concept.

Let’s look at a couple of cases

Subject to a

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
Copy the code

It can be seen from the result that A and B use the same data source.

Topic 2

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);    / / 24
Copy the code
  1. A is passed into change as a parameter. In this case, A and O share the same data, so if O is modified, A will be affected.
  2. When o is reassigned, there is no relation between O and A.

Data type detection

The first judgment method: Typeof

typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol(a)// 'symbol'
typeof null // 'object'
typeof [] // 'object'
typeof {} // 'object'
typeof console // 'object'
typeof console.log // 'function'
Copy the code
  1. The first six are basic data types;
  2. althoughTypeof NULL outputs objectHowever, this is a long-standing JS Bug and does not mean null is a reference data type, nor is NULL itself 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’.
  3. Reference data types, typeof,Except that function is judged to be OKThe rest are ‘object’ and cannot be determined.

The second judgment method: instanceof

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

Because all reference types of data have prototypes, you can determine from the prototype chain.

function myInstanceof(left, right) {
  // Use typeof to determine the underlying data type. If so, return false
  if(typeofleft ! = ='object' || left === null) return false;
  // getProtypeOf is an Object API that can get the parameters of the prototype Object
  let proto = Object.getPrototypeOf(left);
  while(true) {                  // Loop down until you find the same prototype object
    if(proto === null) return false;
    if(proto === right.prototype) return true;// Find the same prototype object, return true
    proto = Object.getPrototypeof(proto); }}// verify that myInstanceof is OK
console.log(myInstanceof(new Number(123), Number));    // true
console.log(myInstanceof(123.Number));                // false
Copy the code

Both methods 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.

Methods: perfect Object. The prototype. ToString

Object.prototype.toString({})       // "[object Object]"
Object.prototype.toString.call({})  // Same result as above, add call also ok
Object.prototype.toString.call(1)    // "[object Number]"
Object.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

Written in full:

function getType(obj){
  let type  = typeof obj;
  if(type ! = ="object") {    // Check typeof first, if it is a basic data type, return directly
    return type;
  }
  // If typeof returns object, regex returns result
  return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/.'$1');  // Note that there is a space between the re
}
/* Code validation, need to pay attention to case, which is typeof judgment, which is toString judgment? Think about the next * /
getType([])     // "Array" typeof [] is object, so toString is returned
getType('123')  // "string" typeof returns directly
getType(window) // "Window" toString returns
getType(null)   Typeof Null is object and toString is required
getType(undefined)   // "undefined" typeof returns directly
getType()            // "undefined" typeof returns directly
getType(function(){}) // "function" typeof can determine, so the first letter is lowercase
getType(/123/g)      / / "RegExp" toString returns
Copy the code