一句代码判断js中所有数据类型

54 阅读2分钟

javascript中有6种基本数据类型:字符串(String)、数字(Number)、布尔(Boolean)、空(Null)、未定义(Undefined)、Symbol。和引用(复杂)类型如:对象(Object)、数组(Array)、函数(Function),以及两个特殊的对象:正则(RegExp)和日期(Date)。 由于jsvascript是动态语言,它的类型运行的时候才知道,所以在开发过程中对类型的判断尤其重要。

javascritp中有好几种判断数据类型的方法,但是根据自己实际开发过程中发现,最常用的方法是如下两种:

1、原始类型中的基本类型( Number 、 String 、 Boolean 、undefined ,Symbol )使用typeof进行判断

console.log("测试number:"+typeof 1);
// number

console.log("测试string:"+typeof "str");
// string

console.log("测试false:"+typeof false);
// boolean

console.log("测试undefined:"+typeof undefined);
// undefined

console.log("看看typeof NaN是啥:"+typeof NaN);
// number

console.log("我想看看Symbol类型:"+typeof Symbol('aa'));
// symbol

可以看到上面这些基本的数据类型使用typeof能正确的返回类型,但是下面这些引用(复杂)类型通过typeof都会返回object

console.log("测试null:"+typeof null);
// object

console.log("测试Object:"+typeof new Object());
// object

console.log("测试Object:"+typeof new Array());
// object

console.log("我想看看数组[1,2,3]类型:"+typeof [1,2,3]);
// object

console.log("我想看看Set类型:"+typeof new Set());
// object

所以对于这些引用类型和null需要使用其它的办法来判断

2、原始类型中的引用(复杂)类型(object,null)使用Object.prototype.toString.call()来判断

const target = Object.prototype.toString;

target.call(null)
// "[object Null]"

target .call(new Object())
// "[object Object]"

target.call(new Array())
// "[object Array]"

target.call([1,2,3])
// "[object Array]"

target .call(new Set())
// "[object Set]"

Object.prototype.toString.call()不仅可以判断复杂的数据类型,还可以判断基本的数据类型

const target = Object.prototype.toString;

target.call(1) // "[object Number]"

target.call('') // "[object String]"

target.call(Symbol()) // "[object Symbol]"

target.call(99n) // "[object BigInt]"

target.call(undefined) // "[object Undefined]"

target.call(true) // "[object Boolean]

3、Function即可以使用typeof也可以使用Object.prototype.toString.call来判断

//方法1
const target = Object.prototype.toString;

target.call(function(){})
// "[object Function]"

方法2
console.log("看看function是啥:"+typeof function(){});
// function

总结:javascript中判断数据类型的方法比较多容易混淆,而且其它方法或多或少有一些问题,所以javascript中判断数据类型记住Object.prototype.toString.call()这个一劳永逸的方法就行了。