js判断数据类型的方法

317次阅读
没有评论

js判断数据类型的方法

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种数据类型。

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

判断对象和构造函数在原型链上是否有关系,如果有关系,返回真,否则返回假。

[] instanceof Array; //true
{} instanceof Object;//true
 new Date() instanceof Date;//true

第三种:使用toString

是Object原型对象上的一个方法,该方法默认返回其调用者的具体类型,基本上所有对象的类型都可以通过这个方法获取到。

  Object.prototype.toString.call('');    //[object String]   
  Object.prototype.toString.call(100);    //[object Number]
  Object.prototype.toString.call([]);     //[object Array]
  Object.prototype.toString.call(new RegExp());    //[object RegExp]

以上就是js判断数据类型的三种方法,大家可以套入代码直接使用哦~更多js学习教程:js教程。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:JavaScript2022-12-16发表,共计1445字。
新手QQ群:570568346,欢迎进群讨论 Python51学习