在某些情况下,您JavaScript可能需要依赖特定的变量来“定义”或“存在”,以便进行下一步。
注意
我不建议这样做,因为JavaScript不应涉及任何业务逻辑,它应该纯粹是基本的验证或UI增强,但是许多人仍然喜欢编写复杂JavaScript,这只会使项目难以维护。
“ typeof ”是检查变量数据类型的有用运算符。 这是由typeof运算符返回的值的列表:
- “数字” –变量是数字。
- “字符串” –变量是一个字符串。
- “布尔值” –变量是布尔值。
- “对象” –变量是一个对象。
- null –变量为null。
- “未定义” –未定义变量。
因此,在这种情况下,要检查变量是否存在或定义,请使用“ typeof ”运算符,并检查返回的值是否为“ undefined ”。
1. typeof ==“未定义”
完整的HTML示例,演示了如何使用“ typeof
”来检查是否定义了变量。
<html>
<body>
<h1>JavaScript : typeof example</h1>
<script type="text/javascript">
var str1 = "mkyong.com";
if(typeof str1 == 'string'){
document.write(str1 + " is a string <br/>");
}
if(typeof str1 == 'undefined'){
document.write("str1 variable is not exists <br/>");
}else{
document.write("str1 variable is exists <br/>");
}
if(typeof str2 == 'undefined'){
document.write("str2 variable is not exists <br/>");
}else{
document.write("str2 variable is exists <br/>");
}
</script>
</body>
</html>
2.演示
在您的网络浏览器中打开上方的HTML文件,将返回以下结果。
mkyong.com is a string
str1 variable is exists
str2 variable is not exists
下载源代码
下载它– typeof-example-example-check-if-variable-is-defined.zip (1 KB)
标签: JavaScript 变量
翻译自: https://mkyong.com/javascript/check-if-variable-is-exists-in-javascript/