JavaScript之判断数据类型

参考资料

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 检验出来的是 objectNaN检验出来的是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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值