首页 > 解决方案 > 如果 (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,因为 != 表示不等于?

标签: javascript

解决方案


在您的代码中,您将 typeof getValue 与未定义的文字类型进行了比较。由于 typeof 实际上为您提供了一个字符串,因此您应该将此值与字符串“未定义”进行比较。

任何一个

if (typeof getValue !== "undefined")

或者

if (getValue !== undefined)

会成功的。


推荐阅读