Universal method for detecting data types

In JS, there are two ways to detect data types, one is typeof data, this method is simple but there are two data types that cannot be detected, one is null, and the other is an array Array

 //值类型
        let str = 'abc'
        let num = 10
        let bol = true
        let und = undefined
        let nul = null
        //引用类型
        let arr = [10, 20, 30]
        let fn = function () { }
        let obj = { name: 'ikun' }

        console.log(typeof str)//'string'
        console.log(typeof num)//'number'
        console.log(typeof bol)//'boolean'
        console.log(typeof und)//'undefined'
        console.log(typeof nul)//'object'
        console.log(typeof arr)//'object'
        console.log(typeof fn)//'function'
        console.log(typeof obj)//'object'

If you want to detect data of null data type and array type, you can use the Object.prototype.toString.call(data) method

        //值类型
        let str = 'abc'
        let num = 10
        let bol = true
        let und = undefined
        let nul = null
        //引用类型
        let arr = [10, 20, 30]
        let fn = function () { }
        let obj = { name: 'ikun' }

        console.log(Object.prototype.toString.call(str))//'[object String]'
        console.log(Object.prototype.toString.call(num))//'[object Number]'
        console.log(Object.prototype.toString.call(bol))//'[object Boolean]'
        console.log(Object.prototype.toString.call(und))//'[object Undefined]'
        console.log(Object.prototype.toString.call(nul))//'[object Null]'
        console.log(Object.prototype.toString.call(arr))//'[object Array]'
        console.log(Object.prototype.toString.call(fn))//'[object Function]'
        console.log(Object.prototype.toString.call(obj))//'[object Object]'

Guess you like

Origin blog.csdn.net/m0_67296095/article/details/124695485