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,因此基本类型不是对象.

0 0