判断数据类型的几种方法

161 阅读1分钟

1.typeof

缺点:typeof null 的值为 Object,无法分辨是 null 还是 Object

typeof undefined // 'undefined' 
typeof '10' // 'String' 
typeof 10 // 'Number' 
typeof false // 'Boolean' 
typeof Symbol() // 'Symbol'
typeof Function // ‘function' 
typeof null // ‘Object’ 
typeof [] // 'Object' 
typeof {} // 'Object'

为什么 typeof null 是 Object

因为在 JavaScript 中,不同的对象都是使用二进制存储的,如果二进制前三位都是0的话,系统会判断为是 Object 类型,而 null 的二进制全是 0,自然也就判断为Object 这个 bug 是初版本的 JavaScript 中留下的,扩展一下其他五种标识位:
000 对象
1 整型
010 双精度类型
100 字符串
110 布尔类型

2.instanceof

原理:

instanceof 原理实际上就是查找目标对象的原型链 
function myInstance(L, R) {
//L 代表 instanceof 左边,R 代表右边
var RP = R.prototype var LP = L.__proto__ 
while (true) { 
    if(LP == null) { 
        return false 
    } 
    if(LP == RP) { 
        return true 
    } 
    LP = LP.__proto__ 
    }
}
console.log(myInstance({},Object));

缺点:只能判断对象是否存在于目标对象的原型链上

function Foo() { } 
var f1 = new Foo();
var d = new Number(1)
console.log(f1 instanceof Foo);// true 
console.log(d instanceof Number); //true
console.log(123 instanceof Number); //false -->不能判断字面量的基本数据类

3.constructor

var d = new Number(1) 
var e = 1 
function fn() { 
    console.log("ming"); 
} 
var date = new Date(); 
var arr = [1, 2, 3]; 
var reg = /[hbc]at/gi; 
console.log(e.constructor);//ƒ Number() { [native code] } 
console.log(e.constructor.name) //Number 
console.log(fn.constructor.name) // Function 
console.log(date.constructor.name)// Date 
console.log(arr.constructor.name) // Array 
console.log(reg.constructor.name) // RegExp

4.Object.prototype.toString.call()

一种最好的基本类型检测方式 Object.prototype.toString.call() ;它可以区分null 、string 、boolean 、 number 、 undefined 、 array 、 function 、object 、date 、 math 数据类型。
缺点:不能细分为谁谁的实例

console.log(Object.prototype.toString.call(undefined)); // "[object Undefined]" 
console.log(Object.prototype.toString.call(null)); // "[object Null]" 
console.log(Object.prototype.toString.call(123)); // "[object Number]" 
console.log(Object.prototype.toString.call("abc")); // "[object String]" 
console.log(Object.prototype.toString.call(true)); // "[object Boolean]" 

function fn() { 
    console.log("ming"); 
} 
var date = new Date(); 
var arr = [1, 2, 3]; 
var reg = /[hbc]at/gi; 
console.log(Object.prototype.toString.call(fn));// "[object Function]" 
console.log(Object.prototype.toString.call(date));// "[object Date]" 
console.log(Object.prototype.toString.call(arr)); // "[object Array]" 
console.log(Object.prototype.toString.call(reg));// "[object RegExp]"