The underlying mechanism of js data type detection

type of data

Number/String/Boolean/Null/Undefined/Object/Symbol/BigInt

The way of data type detection and the underlying mechanism

1. typeof
1. Detection is based on the value of the data type (binary) at the bottom of the computer
2. For example: typeof null // "object" objects exist in the calculation set, and they are all stored in binary starting with 000, and null is also detected, so it is detected The result is that object
3.typeof can only detect basic data types, and detect reference data types (ordinary objects/array objects/regular objects/date objects) are all "object"

let num = 1
console.log(typeof num)//"number"

Two, instanceof
1. Detect whether the current instance belongs to this class. Underlying mechanism: As long as the current class appears on the prototype chain of the instance, the results are all true, that is, all can be found. 2.
Since we can manually modify the pointer of the prototype at will, the detected results are inaccurate
3. Cannot detect basic data types

let obj = {
    
    }
console.log(obj instanceof Array) //false
console.log(obj instanceof Object) //true

Three, constructor
1. Support the detection of basic data types.
2. Detect which class constructs the current instance
3. Defect: Since the pointer of the constructor can be changed manually, the detection is not accurate

let obj = {
    
    }
console.log(obj.constructor === Object)// true
console.log(obj.constructor === Array) //false

4. Object.prototype.toString.call([value]) (the best way to detect the type)
1. The standard method to detect the data type: Object.prototype.toString is not converted into a string, but returns the class to which the current instance belongs Information
2. Standard detection method "[object Number/String/Boolean/Null/Undefined/Symbol/Object/Array/RegExp/Date/Function]"

示例一:
let obj = {
    
    
	name:"精进技术"
}
obj.toString(); => "[object Object]"
toString方法执行, this是obj  所以检测是obj它所属类的信息
推测:是不是只要把Object.prototype.toString执行,让它里面的this变为要检测的变量/实例,那就能返回当前变量/实例所属的类的信息
console.log(Object.prototype.toString.call(obj))//"[object Object]"

示例二:
let arr = []
console.log(Object.prototype.toString.call(arr))//"[object Array]"

To sum up, the detection of each data type has its own limitations. In order to better adapt to the comprehensive data type detection method, it is necessary to combine various data types into a general and relatively perfect type detection method. .

Common methods for detecting data types
let class2Type = {
    
    }
let toString = class2Type.toString; //就是 Object.prototype.toString
//形成数据类型的映射表
["Boolean", "Number", "String", "Function", "Array", "Date", "RegExp", "Object", "Error", "Symbol"].forEach((name) => {
    
    
    class2Type[`[object ${
      
      name}]`] = name.toLowerCase()
})

function toType(obj) {
    
    
    if (obj == null) {
    
    
        //传递的值是null或者undefined, 就返回对应的字符串
        return obj + ''
    }
    //基本数据类型都采用typeof检测
    return typeof obj === "object" || typeof obj === "function" ? class2Type[toString.call(obj)] || "object" :
        typeof obj
}

console.log(toType([])) //array
console.log(toType({
    
    })) //object
console.log(toType('')) //string
console.log(toType(null)) //string


//将数据类型检测封装成一个工具包,仅供参考
(function() {
    
    
    let class2Type = {
    
    }
    let toString = class2Type.toString; //就是 Object.prototype.toString
    //形成数据类型的映射表
    ["Boolean", "Number", "String", "Function", "Array", "Date", "RegExp", "Object", "Error", "Symbol"].forEach((name) => {
    
    
        class2Type[`[object ${
      
      name}]`] = name.toLowerCase()
    })

    function toType(obj) {
    
    
        if (obj == null) {
    
    
            //传递的值是null或者undefined, 就返回对应的字符串
            return obj + ''
        }
        //基本数据类型都采用typeof检测
        return typeof obj === "object" || typeof obj === "function" ? class2Type[toString.call(obj)] || "object" :
            typeof obj
    }
    window.toType = toType
})()
console.log(toType([])) //array
console.log(toType({
    
    })) //object
console.log(toType('')) //string
console.log(toType(null)) //string

Guess you like

Origin blog.csdn.net/weixin_47818125/article/details/128311324