
JavaScript中有基本数据类型和引用数据类型两大数据类型,基本数据类型有string、number、Boolean、null、undefined、symbol。引用数据类型有Object、Function、Array、Date、RegExp 。这些数据类型又是如何判断的呢?本文介绍js判断数据类型的三种方法:1、使用typeof ;2、使用instanceof;3、使用toString。
第一种:使用typeof
返回一个表示数据类型的字符串,返回结果包括:number、boolean、string、object、undefined、function等6种数据类型。
1 2 3 4 5 6 7 8 9 10 11 | alert(typeof "helloworld" ) ------------------> "string"
alert(typeof 123) ------------------> "number"
alert(typeof [1,2,3]) ------------------> "object"
alert(typeof new Function()) ------------------> "function"
alert(typeof new Date ()) ------------------> "object"
alert(typeof new RegExp()) ------------------> "object"
alert(typeof Symbol()) ------------------> "symbol"
alert(typeof true) ------------------> "true"
alert(typeof null) ------------------> "object"
alert(typeof undefined) ------------------> "undefined"
alert(typeof 'undefined' ) ------------------> "string"
|
第二种:使用instanceof
判断对象和构造函数在原型链上是否有关系,如果有关系,返回真,否则返回假。
1 2 3 | [] instanceof Array;
{} instanceof Object;
new Date () instanceof Date ;
|
第三种:使用toString
是Object原型对象上的一个方法,该方法默认返回其调用者的具体类型,基本上所有对象的类型都可以通过这个方法获取到。
1 2 3 4 | Object.prototype.toString.call( '' );
Object.prototype.toString.call(100);
Object.prototype.toString.call([]);
Object.prototype.toString.call( new RegExp());
|
以上就是js判断数据类型的三种方法,大家可以套入代码直接使用哦~更多js学习教程:js教程。