前言
js的数据类型判断是面试题里的常考题型,常用的判断方法有四种:
-
Array.isArray()
-
typeof
-
Object.prototype.toString.call()
-
obj instanceof Object
四种方法各有优缺点,今天就让我们一起来学习一下吧
数据类型
首先要明确一点,Javascipt中的数据类型分为基本数据类型(值类型) 和 引用类型(对象类型)
基本数据类型:
-
number
-
string
-
boolean
-
null
-
undefined
-
Symbol(es6新增,表示独一无二的值)
引用数据类型:
-
- object(对象)
-
- Array(数组)
-
- Function(函数)
-
- Date(日期)
判断方法
一、Array.isArray()
该方法只能用于判断对象是否为数组,返回值是布尔值(true、false)
二、typeof
console.log(typeof(123)) //number
console.log(typeof('abc')) //string
console.log(typeof(true)) //boolean
console.log(typeof(undefined)) //undefined
console.log(typeof(null)) //object
console.log(typeof(Function)) //function
console.log(typeof([])) //object
console.log(typeof({})) //object
可以发现,typeof可以精准判断除null以外的基本数据类型,由于不同的对象底层都是用二进制表示的,在js中,如果二进制前三位都为0,就会被typeof判断为object,其中null的二进制全是0,故返回值为object。同时typeof也可以很智能地判断出函数类型。所以通常情况下,我们会使用typeof判断基本数据类型
三、Object.prototype.toString.call()
先看基本数据类型判断代码:
console.log(Object.prototype.toString.call(123)); //[object Number]
console.log(Object.prototype.toString.call('abc')); //[object String]
console.log(Object.prototype.toString.call(null)); //[object Null]
console.log(Object.prototype.toString.call(true)); //[object Boolean]
console.log(Object.prototype.toString.call(undefined)); //[object Undefined]
我们发现,Object.prototype.toString.call()方法可以精准的判断出基本数据类型,连typeof()“ 错误判断 ”的null也可以识别出,那对于引用数据类型呢?
console.log(Object.prototype.toString.call([1, 2])); //[object Array]
console.log(Object.prototype.toString.call({name: 'a'})); //[object Object]
console.log(Object.prototype.toString.call(Function)); //[object Function]
console.log(Object.prototype.toString.call(new Date)); //[object Date]
可以看见,引用类型我们也能精准判断!那这简直就是万能公式啊!唯一的缺陷就是这些代码的返回值,除了有我们想要的类型以外,还有[]和object,那我们有没有啥办法只得到我们想要的数据类型呢?答案是肯定的!只要通过 slice() 就能实现:
object.prototype.toString.call(undefined).slice(8, -1) //Undefined
Object.prototype.toString.call(null).slice(8,-1) //Null
Object.prototype.toString.call([]).slice(8,-1) //Array
Object.prototype.toString.call(Function).slice(8,-1) //Function
四、obj instanceof Object
obj instanceof Object 是用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性。obj是你要判断的内容,Object放置类型。
function instance_of(L,R){
let O = R.prototype
L = L.__proto__
while(L !== null){
if(L === O) return true
L = L.__proto__
}
return false
}
instance_of([], Array)
function instance_of(L,R){
let O = R.prototype
L = L.__proto__
while(L !== null){
if(L === O) return true
L = L.__proto__
}
return false
}
instance_of([], Number)
结语
本期内容到这就结束了,虽然还有其他的一些方法判断,但其实只要掌握以上方法,你就已经可以解决js中所有的数据类型的判断了,如果本期内容有什么错误,欢迎各位小伙伴在评论区里指正,如果有什么更好的方法,也欢迎提出哦~