js如何判断数据类型

一、常用的js数据类型

基本数据类型 :String、Number、Boolean、Null、Undefined
复杂数据类型 :Object

二、js数据类型判断

// 初始化一些数据用来判断
let str = "字符串类型" 
let bool = true   
let num = 123 
let nulll = null  
let undef   
let arr = []   
let obj = {}   
let sum = function () {}  

1.使用typeof进行判断

console.log(typeof str) // string
console.log(typeof bool) // boolean
console.log(typeof num) // number
console.log(typeof nulll) // object
console.log(typeof undef) // undefined
console.log(typeof arr) // object
console.log(typeof obj) // object
console.log(typeof sum) // function

{callout color=”#66edff”}
使用typeof进行判断数据类型,只能够判断基本数据类型string number boolean 以及 function,而null和object不能够进一步的判断。
{/callout}
2.使用A instanceof B进行判断

console.log(str instanceof String) // false
console.log(bool instanceof Boolean) // false
console.log(num instanceof Number) // false
console.log(nulll instanceof Object) // false
console.log(undef instanceof Object) // false
console.log(arr instanceof Array) // true
console.log(obj instanceof Object) // true
console.log(sum instanceof Function) // true

{callout color=”#66edff”}
使用A instanceof B的方式进行判断,字面意思,A是否是B的实例,可以判断出Array和Object类型,但是undefined和null不能区分数据类型,基础的数据类型,因为不是使用new出来的,也测试不出来。
{/callout}
3.使用Object.prototype.toString.call()进行判断

console.log(Object.prototype.toString.call(str)) // [object String]
console.log(Object.prototype.toString.call(bool)) // [object Boolean]
console.log(Object.prototype.toString.call(num)) // [object Number]
console.log(Object.prototype.toString.call(nulll)) // [object Null]
console.log(Object.prototype.toString.call(undef)) // [object Undefined]
console.log(Object.prototype.toString.call(arr)) // [object Array]
console.log(Object.prototype.toString.call(obj)) // [object Object]
console.log(Object.prototype.toString.call(sum)) // [object Function]

{callout color=”#66edff”}
Object.prototype.toString()方法可以返回一个表示该对象的字符串'[object type]’,为了每个对象都能通过 Object.prototype.toString() 来检测,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用,传递要检查的对象作为第一个参数,称为 thisArg。
{/callout}

三、封装成函数

function judgeType (data) {
  return Object.prototype.toString.call(data).slice(8, -1)
}

judgeType('jkl') // 'String'
judgeType(123) // 'Number'
judgeType(true) // 'Boolean'
judgeType(null) // 'Null'
judgeType(undefined) // 'Undefined'
judgeType([]) // 'Array'
judgeType({}) // 'Object'
judgeType(function sum () {}) // 'Function'
judgeType(new Set()) // 'Set'
judgeType(new Map()) // 'Map'
© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享
评论 共1条

请登录后发表评论

    暂无评论内容