javascript - 如果 (myVar != "未定义")
问题描述
我想检查 localWebstorage 中的一个项目是否还没有被赋予一个值。我尝试这样做:
//Change localStorage.intervalSetting from 'Undefined' to 'Never'
function initialIntervalSetting() {
var getValue = localStorage.intervalSetting;
if (typeof getValue === undefined) {
localStorage.intervalSetting = "option1";
alert("Changed the localWebstorage item from undefined to "option1");
}
else {
alert("JavaScript thinks that the item is not undefined");
}
}
但是,这不起作用..这里提出了问题: 如何在 JavaScript 中检查“未定义”?有人回答:
if (typeof getValue != "undefined") {
localStorage.intervalSetting = "option1";
}
他们建议将 === 替换为 !=
出于某种原因,这可行-如何?
(getValue != "undefined") 不应该返回 false,因为 != 表示不等于?
解决方案
在您的代码中,您将 typeof getValue 与未定义的文字类型进行了比较。由于 typeof 实际上为您提供了一个字符串,因此您应该将此值与字符串“未定义”进行比较。
任何一个
if (typeof getValue !== "undefined")
或者
if (getValue !== undefined)
会成功的。
推荐阅读
- python - 如何在 Google App Store Cloud Shell 中配置 pycodestyle
- python - How to get just summary line from python docstring?
- google-apps-script - 如何在 Google Apps 脚本中设置计时器?
- scrapy - 刮痧和尊重robots.txt
- python - 如何使用熊猫根据行值条件更改列数据类型
- java - 我们可以在 selenium webdriver 中使用 for 循环的场景有哪些?
- mule - 从存储库打开并处理 Mulesoft 项目
- gradle - 如何在 IntelliJ 中调试我的 Grails 应用程序?
- html - 如何显示primeNg inputSwitch的未选中元素?
- naming-conventions - 在命名我的函数以提供规律性时,我是否应该放弃语法正确性?