javascript - 如果(myVar!= "undefined")

标签 javascript

我想检查 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/

相关文章:

javascript - 获取 <script> 标签的内容

javascript - 如何使用 Codeigniter、Javascript 和 GET 表单在 URL 中强制使用逗号

javascript - 如何使用 javascript 将图像从 PNG 转换为 JPEG?

javascript - 无法在加载事件上提交按钮

javascript - 如何从 JavaScript 检查 session 是否存在

javascript - 更改 URL 背景的书签

javascript - 从网站下载图片到桌面

javascript - Redis 数据库设计不当

javascript - 访问范围输入值以将其显示在 slider 顶部

Javascript replace() 方法失败?