JS类型检测(typeof和instanceof)
来源:互联网 发布:sizeof 数组 编辑:程序博客网 时间:2024/04/29 09:31
要检测一个变量是不是基本的数据类型,typeof是最佳的工具。typeof操作符是确定一个变量是字符串、数值、布尔值、还是undefined的最佳工具。如果一个变量是一个对象或者null,那么typeof就会返回“object”;
var s = “Bob”;
var b = true ;
var i = 22;
var u;
var n =null;
var o = new Object();
alert(typeof(s)); //string
alert(typeof(b)); //boolean
alert(typeof(i));//number
alert(typeof(u));//undefine
alert(typeof(n));//object
alert(typeof(o));//object
虽然typeof在检测基本数据类型时是非常的得力的助手,但是在检测对象类型的时候用处就不大了,此时我们就需要instanceof操作符了,语法如下
result = variable instanceof constructor
如果变量是给定的引用类型那么就会返回true,否则就会返回false
alert(person instanceof Object); // 变量person是否是Object
alert(colors instanceof Array); //变量colors是否是Arrray
根据规定,所有的类型的值都是Object的实例,因此在检测一个应用类型值和Object的构造函数时,instanceof都会返回true,如果使用instanceof操作符检测基本类型的值,则该操作符时钟会返回false,因此基本类型不是对象.
- JS类型检测(typeof和instanceof)
- JavaScript之检测类型(typeof与instanceof)
- js中的类型判断typeof、instanceof、constructor和prototype
- js中的typeof和instanceof的用法和区别(附类型判断方法)
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS typeof和instanceof用法
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- js中的instanceof 和 typeof
- React dynamicTableView
- Python 处理微信网页版消息中的emoji表情在命令行中显示
- file类的常用方法
- Java 多线程7:ThreadLocal 类
- word2vector & paragraph2vector 技术分享
- JS类型检测(typeof和instanceof)
- C#中的协变性与逆变性, Part Two: 数组协变性
- 【校招笔试】通过考试(dp)
- 京东2017实习生招聘在线笔试编程题题解
- SQL回顾二
- P3369 【模板】普通平衡树(Treap/SBT)
- POJ 2576 Tug of War 二维费用背包
- FlyMCU烧写程序结束后不自动运行程序,需要手动复位后才可以运行的解决
- C#编写简单的数据库增删改查(二)