JavaScript判断数据类型

2020-12-23 11:07发布

1、定义检测数据

const num  = 123;
const str  = 'aaa';
const bool = true;
const arr  = [1, 2];
const json = {name:'aaa', num:111};
const func = () => console.log('function');
const und  = undefined;
const nul  = null;
const date = new Date();
const reg  = /[a-z]/;
const error= new Error();

2、typeOf()检测

typeof对于原始类型(除了Null)是可以检测到的,但是引用类型就统一返回object

console.log(
    typeof num,		// number
    typeof str,		// string
    typeof bool,	// boolean
    typeof arr,		// object
    typeof json,	// object
    typeof func,	// function 
    typeof und,		// undefined 
    typeof nul,		// object
    typeof date,	// object
    typeof reg,		// object
    typeof error	// object);12345678910111213

arr, json, nul, date, reg, error 全部被检测为object类型,其他的变量能够被正确检测出来。当需要变量是否是number, string, boolean, function, undefined, json类型时,可以使用typeof进行判断。其他变量是判断不出类型的,包括null。

3、instance of()检测

instance of 用于检测构造函数的原型是否出现在某个实例函数的原型链上

console.log(
    num instanceof Number,		// false
    str instanceof String,		// false
    bool instanceof Boolean,	// false
    arr instanceof Array,		// true
    json instanceof Object,		// true
    func instanceof Function,	// true
    und instanceof Object,		// false
    nul instanceof Object,		// false
    date instanceof Date,		// true
    reg instanceof RegExp,		// true
    error instanceof Error		// true)12345678910111213

4、Object.prototype.toString.call()检测

最好的方法是使用 Object.prototype.toString方法,它可以检测到任何类型,返回的结果是[object Type]的形式,基本可以实现所有类型的检测,我们用下面的代码来演示一下。

//实现一个检测类型的公共接口
checkType = data => Object.prototype.toString.call(data);

//根据自己的需求进行扩展,记住类型的首字母要大写
Object.prototype.toString.call(num);			// "[object Number]"
Object.prototype.toString.call(str);			// "[object String]"
Object.prototype.toString.call(bool);			// "[object Boolean]"
Object.prototype.toString.call(arr);			// "[object Array]"
Object.prototype.toString.call(json);			// "[object JSON]"
Object.prototype.toString.call(func);			// "[object Function]"
Object.prototype.toString.call(und);			// "[object Undefined]"
Object.prototype.toString.call(nul);			// "[object Null]"
Object.prototype.toString.call(date);			// "[object Date]"
Object.prototype.toString.call(reg);			// "[object RegExp]"
Object.prototype.toString.call(error);			// "[object Error]"


作者:SmallTeddy

链接:https://blog.csdn.net/SmallTeddy/article/details/108821470

来源:CSDN
著作权归作者所有,转载请联系作者获得授权,切勿私自转载。