js判断数据类型的方法

2026-01-22 0 1,546

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教程。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 web开发 js判断数据类型的方法 https://www.zhiup.top/10057.html

相关