面试题:如何判断数据类型

158 阅读1分钟

js数据类型检测语法: typeof 数据
但是typeof有两种数据类型无法检测 : null 和 数组 (得到'object')

        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: '张三' }

        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'

image.png
那么如果需要检测null和数组类型的数据如何处理? 在这里给大家介绍一种万能的数据检测方法 Object.prototype.toString.call( 数据 )

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]'

image.png
原因: 在Object.prototype中有一个方法叫做toString, 返回一个固定格式字符串'[object 数据类型]',这样所有的数据类型就都可以检测出来