品易云推流 关闭
文章详情页
文章 > JavaScript > js判断数据类型的方法

js判断数据类型的方法

js判断数据类型

头像

宋雪维

2021-01-12 14:30:333890浏览 · 0收藏 · 0评论

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

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图