JS typeof和instanceof用法
2013-05-23 21:07
441 查看
typeof是一个一元运算,放在一个运算数之前,运算数可以是任意类型。
typeof用以获取一个变量或者表达式的类型,typeof一般只能返回如下几个结果:
number,boolean,string,function(函数),object(NULL,数组,对象),undefined。
如:
alert(typeof (123));//typeof(123)返回"number"
alert(typeof ("123"));//typeof("123")返回"string"
我们可以使用typeof来获取一个变量是否存在,如if(typeof a!="undefined"){},而不要去使用if(a)因为如果a不存在(未声明)则会出错,
正因为typeof遇到null,数组,对象时都会返回object类型,所以当我们要判断一个对象是否是数组时
或者判断某个变量是否是某个对象的实例则要选择使用另一个关键语法instanceof
instanceof用于判断一个变量是否某个对象的实例,如var a=new Array();alert(a instanceof Array);会返回true,
同时alert(a instanceof Object)也会返回true;这是因为Array是object的子类。
再如:function test(){};var a=new test();alert(a instanceof test)会返回true。
typeof用以获取一个变量或者表达式的类型,typeof一般只能返回如下几个结果:
number,boolean,string,function(函数),object(NULL,数组,对象),undefined。
如:
alert(typeof (123));//typeof(123)返回"number"
alert(typeof ("123"));//typeof("123")返回"string"
我们可以使用typeof来获取一个变量是否存在,如if(typeof a!="undefined"){},而不要去使用if(a)因为如果a不存在(未声明)则会出错,
正因为typeof遇到null,数组,对象时都会返回object类型,所以当我们要判断一个对象是否是数组时
或者判断某个变量是否是某个对象的实例则要选择使用另一个关键语法instanceof
instanceof用于判断一个变量是否某个对象的实例,如var a=new Array();alert(a instanceof Array);会返回true,
同时alert(a instanceof Object)也会返回true;这是因为Array是object的子类。
再如:function test(){};var a=new test();alert(a instanceof test)会返回true。
相关文章推荐
- JS类型检测(typeof和instanceof)
- js的instanceof 运算符vs typeof 运算符
- JS typeof与instanceof的区别
- js typeof 和instanceof的区别
- typeof和instanceof在js中的应用
- js基础2-深入理解javascript之typeof和instanceof
- typeof和instanceof简介及用法
- JS中的instanceof和typeof
- js之typeof与instanceof 小解
- 如何判断js中的数据类型:typeof、instanceof、 constructor、 prototype方法比较
- js之【typeof和instanceof的区别】
- JS中的instanceof和typeof
- 实例详解JS中的类型检测1:typeof和instanceof
- typeof和instanceof简介及用法
- js typeof 与 instanceof的区别
- js中的数据类型和typeof
- js instanceof、typeof、Object.prototype.toString.call(obj)的用法和区别
- js中substr,substring,indexOf,lastIndexOf等的用法
- js中substr,substring,indexOf,lastIndexOf的用法小结
- linux c typeof创建结构体元素类型用法