javascript中有6种基本数据类型:字符串(String)、数字(Number)、布尔(Boolean)、空(Null)、未定义(Undefined)、Symbol。和引用(复杂)类型如:对象(Object)、数组(Array)、函数(Function),以及两个特殊的对象:正则(RegExp)和日期(Date)。 由于jsvascript是动态语言,它的类型运行的时候才知道,所以在开发过程中对类型的判断很重要。
javascritp中有好几种判断数据类型的方法,但是根据自己实际开发过程中发现,最常用的方法是如下两种:
1、原始类型中的基本类型( Number 、 String 、 Boolean 、undefined ,Symbol )使用typeof进行判断
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| console.log("测试number:"+typeof 1);
console.log("测试string:"+typeof "str");
console.log("测试false:"+typeof false);
console.log("测试undefined:"+typeof undefined);
console.log("看看typeof NaN是啥:"+typeof NaN);
console.log("我想看看Symbol类型:"+typeof Symbol('aa'));
JS
|
可以看到上面这些基本的数据类型使用typeof能正确的返回类型,但是下面这些引用(复杂)类型通过typeof都会返回object
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| console.log("测试null:"+typeof null);
console.log("测试Object:"+typeof new Object());
console.log("测试Object:"+typeof new Array());
console.log("我想看看数组[1,2,3]类型:"+typeof [1,2,3]);
console.log("我想看看Set类型:"+typeof new Set());
JS
|
所以对于这些引用类型和null需要使用其它的办法来判断
2、原始类型中的引用(复杂)类型(object,null)使用Object.prototype.toString.call()来判断
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const target = Object.prototype.toString;
target.call(null)
target .call(new Object())
target.call(new Array())
target.call([1,2,3])
target .call(new Set())
JS
|
Object.prototype.toString.call()不仅可以判断复杂的数据类型,还可以判断基本的数据类型
1 2 3 4 5 6 7 8 9 10 11 12 13
| const target = Object.prototype.toString;
target.call(1)
target.call('')
target.call(Symbol())
target.call(99n)
target.call(undefined)
target.call(true)
JS
|
3、Function即可以使用typeof也可以使用Object.prototype.toString.call来判断
1 2 3 4 5 6 7 8 9
| const target = Object.prototype.toString;
target.call(function(){})
方法2 console.log("看看function是啥:"+typeof function(){});
JS
|
总结:javascript中判断数据类型的方法比较多容易混淆,而且其它方法或多或少有一些问题,所以javascript中判断数据类型记住Object.prototype.toString.call()这个一劳永逸的方法就行了。