参考资料
JavaScript专题之类型判断(上) · Issue #28 · mqyqingfeng/Blog (github.com)
typeof
typeof 是一元操作符,放在其单个操作数的前面,操作数可以是任意类型。返回值为表示操作数类型的一个字符串。
但是呢,它除了对基本数据类型(undefined、Number、String、Boolean)可以做出精确的判断,但是对于null
是不能的。对于引用类型几乎无法做出精确的判断。
console.log(typeof 123);//number
console.log(typeof undefined);//undefined
console.log(typeof true);//boolean
console.log(typeof "123");//string
console.log(typeof null);//obeject
console.log(typeof NaN);// number
console.log(typeof {});//object
console.log(typeof function(){});// function
console.log(typeof new Date());//object
console.log(typeof new Array());//oject
console.log(typeof new Map());//object
console.log(typeof new RegExp());//object
console.log(typeof class{});//function
通过上面的代码,我们可以看出,对于引用类型,基本无法判断出是哪一种,都是返回的object
。
还有需要注意的是对于null
检验出来的是 object
,NaN
检验出来的是number
。
对于null
,直接使用===
判断就好了
总结:
typeof
一般用来判断基本数据类型,除了判断null会输出"object",其它都是正确的
typeof
判断引用数据类型时,除了判断函数会输出"function",其它都是输出"object"
instanceof
instanceof 可以准确的判断引用数据类型,它的原理是检测构造函数的
prototype
属性是否在某个实例对象的原型链上
object instanceof constructor
原理代码
function myIntanceof(left,right){
// 判断是否是基本数据类型,如果是则返回false
if(typeof left!== "object" || typeof left === null ) return false;
if(typeof right !== 'function') {
throw ("not a funciton");
}
let proto = Object.getPrototypeOf(left);
while(true){
if(proto === null) return false;// 找不到的情况
if(proto === right.prototype) return true;
proto = Object.getPrototypeOf(proto);
}
}
let s = '123';
let s1 = new String("123");
console.log(myIntanceof(s,String));// false
console.log(myIntanceof([123],Array));
console.log(myIntanceof(s1,String));
使用constructor来判断
缺点是不能判断null 和 undefined
Object.prototype.toString.call()
var number = 1; // [object Number]
var string = "123"; // [object String]
var boolean = true; // [object Boolean]
var und = undefined; // [object Undefined]
var nul = null; // [object Null]
var obj = { a: 1 }; // [object Object]
var array = [1, 2, 3]; // [object Array]
var date = new Date(); // [object Date]
var error = new Error(); // [object Error]
var reg = /a/g; // [object RegExp]
var func = function a() {}; // [object Function]
console.log(Object.prototype.toString.call(Math)); // [object Math]
console.log(Object.prototype.toString.call(JSON)); // [object JSON]
console.log(Object.prototype.toString.call(arguments)); // [object Arguments]
通过Object.prototype.toString.call()
返回的字符串,我们就可以判断数据的具体类型的。
对于数组,我们还可以使用Array.isArray()
。
判断空对象
function isEmptyObject(obj){
for(let name in obj){
return false;
}
return true;
}
console.log(isEmptyObject({}));// true