js中typeof和instanceof的区别
来源:互联网 发布:成都php培训费用要多少 编辑:程序博客网 时间:2024/06/05 18:37
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
- js中typeof和instanceof的区别
- js中typeof和instanceof的区别
- js中instanceof和typeof的区别
- 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的区别
- JS中typeof与instanceof的区别
- JS中typeof与instanceof的区别
- JS中typeof与instanceof的区别
- mosquitto鉴权插件的开发与说明(一)
- ORA-28040: No matching authentication protocol 解决
- C#事件与委托详解
- js时实验证
- windows10中使用docker命令启动Ubuntu容器
- js中typeof和instanceof的区别
- html介绍
- spark源码阅读二-spark application运行过程
- Java线程池与数据库连接池区别
- c++ string的用法
- java面试题--获取重叠字符串的个数组成一个新字符串
- 享元模式
- JAVA获取网络图片保存本地
- git 操作