js中typeof和instanceof的区别
2017-08-02 17:54
471 查看
ECMA中变量的类型有两种:基本类型值和引用类型值。基本类型值指的是简单的数据段,包括Number、String、Boolean、Function、Undefined以及Object。
typeof用来判断基本类型值,返回值是一个字符串,例:
如果这个值未定义
var message;
alert(typeof message); //undefined
如果这个值是布尔值
var message=true;
alert(typeof message); //boolean
如果这个值是字符串
var message="abc";
alert(typeof message); //string
如果这个值是数值
var message=123;
alert(typeof message); //number
如果这个值是对象或null
var message=new Object();
alert(typeof message); //Object
var message=null;
alert(typeof message); //Object
如果这个值是函数
var message=function(){};
alert(typeof message); //function
因此可以看出typeof返回的是一个变量的基本类型,且必须是Number、String、Boolean、Function、Undefined、Object中的一种。
此外,typeof还可以判断一个变量是否存在,例:
if(typeof a != "undefined"){
//变量存在
}
instanceof用来判断某个对象是否是另一个对象的实例,返回值是一个布尔值,例:
var a ={};
alert(a instanceof Object); //true
var a =[];
alert(a instanceof Array); //true
需要注意的是,instanceof只能用来判断对象和函数,不能用来判断字符串和数字等,例:
var a ="123";
alert(a instanceof String); //false
var b=new String();
alert(b instanceof String); //true
typeof用来判断基本类型值,返回值是一个字符串,例:
如果这个值未定义
var message;
alert(typeof message); //undefined
如果这个值是布尔值
var message=true;
alert(typeof message); //boolean
如果这个值是字符串
var message="abc";
alert(typeof message); //string
如果这个值是数值
var message=123;
alert(typeof message); //number
如果这个值是对象或null
var message=new Object();
alert(typeof message); //Object
var message=null;
alert(typeof message); //Object
如果这个值是函数
var message=function(){};
alert(typeof message); //function
因此可以看出typeof返回的是一个变量的基本类型,且必须是Number、String、Boolean、Function、Undefined、Object中的一种。
此外,typeof还可以判断一个变量是否存在,例:
if(typeof a != "undefined"){
//变量存在
}
instanceof用来判断某个对象是否是另一个对象的实例,返回值是一个布尔值,例:
var a ={};
alert(a instanceof Object); //true
var a =[];
alert(a instanceof Array); //true
需要注意的是,instanceof只能用来判断对象和函数,不能用来判断字符串和数字等,例:
var a ="123";
alert(a instanceof String); //false
var b=new String();
alert(b instanceof String); //true
相关文章推荐
- js中typeof和instanceof的区别
- JS中 typeof 与 instanceof 的区别
- JS中typeof与instanceof的区别
- JS中typeof与instanceof的区别
- JS中typeof与instanceof的区别
- JS中typeof与instanceof的区别
- JS中typeof与instanceof的区别
- JS中typeof与instanceof的区别
- JS中typeof与instanceof的区别
- JS中typeof与instanceof之间的区别总结
- JS中typeof与instanceof的区别
- JS中typeof与instanceof的区别
- JS中typeof与instanceof的区别
- JS中typeof与instanceof的区别
- js中typeof和instanceof用法区别
- Js--- typeof 与 instanceof的区别
- JS中typeof与instanceof之间的区别总结
- js中instanceof与typeof的区别以及instanceof的门道
- 每日学习心得:Js获取Checkboxlist所选值、instanceof 和typeof区别、为Array添加contains方法
- js中typeof与instanceof用法的区别