Javascript:似乎 typeof 不起作用

Han*_*ger 3 javascript

我想仅在未设置时在 javascript 对象中设置值。我的(测试)函数如下所示:

var test = function(){
    this.value = {};

    this.setValue = function(seperator, newValue){
        console.log((this.value[seperator] === "undefined"));  //Why both times false?
        if(typeof(this.value[seperator] === "undefined")){
            this.value[seperator] = newValue;
        }else{
            //noop
        }
        console.log(this.value[seperator]);
    }
}
var blubb = new test();

blubb .setValue("foo","bar");
blubb .setValue("foo","notme");
Run Code Online (Sandbox Code Playgroud)

在 js 控制台中它返回

false
bar
false
notme
Run Code Online (Sandbox Code Playgroud)

有人能告诉我为什么我的“未定义”测试两次都告诉我没有定义吗?

提前致谢

ant*_*rat 5

因为undefined在 JS 中不是字符串,它是全局对象的属性,您可以使用===.

===不仅会比较值,还会比较它们的类型:

1 === "1" // false
1 == "1"  // true
Run Code Online (Sandbox Code Playgroud)

尝试这个:

console.log(( typeof this.value[seperator] === "undefined"));
Run Code Online (Sandbox Code Playgroud)

typeof运算符将变量类型转换为字符串,只有这样你才能检查变量是否等于字符串undefined

在你的第二段代码中:

if(typeof(this.value[seperator] === "undefined")){
Run Code Online (Sandbox Code Playgroud)

typeof在变量外部使用运算符,因此您的代码首先检查this.value[seperator] === "undefined"它是否返回false给您,然后您通过“typeof false”进行检查,它将boolean为您返回。

在最后一步中,您的代码将转换为:

if( "boolean" ){
Run Code Online (Sandbox Code Playgroud)

这总是true因为字符串不为空。