javascript中,可以通过判断变量的值是否为“null”或者数据类型是否为“undefined”来检测变量是否存在,语法“if(typeof(a)=="undefined"||a==null){//不存在}else{//存在}”。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
实际开发过程中,会有判断一个变量是否存在的场景 。
只需要使用判断变量的值是否为null或者数据类型是否为undefined;如果是,则不存在。
首先想到的是
if(a==undefined){
console.log("a is undefined")
}else{
console.log("a is defiend")
}
这里会报错,有可能产生阻塞,而且不够优雅

解决方法:
<script type="text/javascript">
// var a='xixi';
if(typeof(a) == "undefined" || a == null)
alert("a is undefined");
else
alert("a is defined");
</script>
typeof是一个运算符,用于查看数据类型,有2种使用方式:
typeof(表达式)
typeof 变量名
第一种是对表达式做运算,第二种是对变量做运算。
typeof运算符的返回类型为字符串,值包括如下几种:
使用if (typeof(a)=="undefined")
即可判断变量a是否未定义。
【推荐学习:javascript高级教程】
以上就是javascript怎么检测变量是否存在的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章!