您现在的位置是:首页 > Javascript
当前栏目
js判断数据类型的方法
2023-03-15 23:17:06 时间
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教程。
相关文章
- TiDB Binlog 组件正式开源
- 使用Visual Studio Code对Node.js进行断点调试
- 推荐!数据可视化的十种优秀JavaScript图表库
- Node.js在复杂集成场景下占据统治地位的五个理由
- 玩转Node.js单元测试
- Node.js中内存泄漏分析
- Angular对React:一场关于Web开发者支持率的史诗对决
- 热点推荐:什么是后端开发?
- 谈谈Spring boot 启动层面的开发
- 使用NodeJS将文件或图像上传到服务器
- 编写React组件的最佳实践
- JavaScript MV*框架最值得关注的七个亮点
- 前端开发指南:如何利用PHP Cake框架构建应用
- 基于React与Vue后,移动开源项目Weex如何定义未来
- NodeJS和C++之间的类型转换
- jQuery中的常用到的三十九个技巧
- 官宣|Google Developers中国网站发布!
- NodeJS和C++之间的类型转换
- .NET Core首例Office开源跨平台组件(NPOI Core)
- 如何写出漂亮的React组件