我想检查 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");
}
}
但是,这不起作用......问题在这里提出: How to check for "undefined" in JavaScript?有人回答:
if (typeof getValue != "undefined") {
localStorage.intervalSetting = "option1";
}
他们建议用 != 替换 ===
出于某种原因,这有效-如何???
(getValue != "undefined") 不应该返回 false 因为 != 意味着不等于吗?
最佳答案
在您的代码中,您将 typeof getValue 与未定义的文字类型进行了比较。由于 typeof 实际上为您提供了一个字符串,因此您应该将该值与字符串“undefined”进行比较。
或者
if (typeof getValue !== "undefined")
或者
if (getValue !== undefined)
就可以了。
关于javascript - 如果(myVar!= "undefined"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50672434/