Javascript :似乎typeof不起作用

Javascript : Seems like typeof doesn't work

本文关键字:不起作用 typeof 似乎 Javascript      更新时间:2023-09-26

我想只在未设置时在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");

在 JS 控制台中,它返回

false
bar
false
notme

有人可以告诉我为什么两次我的"未定义"测试都告诉我没有定义吗?

提前致谢

因为 JS 中的 undefined 不是字符串,它是全局对象的属性,您可以使用 === 按类型进行比较。

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

1 === "1" // false
1 == "1"  // true

试试这个:

console.log(( typeof this.value[seperator] === "undefined"));

typeof运算符将变量类型转换为字符串,然后您才能检查变量是否等于字符串undefined

在第二段代码中:

if(typeof(this.value[seperator] === "undefined")){

你在变量之外使用typeof运算符,所以你的代码首先检查是否this.value[seperator] === "undefined"然后它返回false给你,然后你通过"typeof false"进行检查,它将为你返回boolean

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

if( "boolean" ){

这始终true因为字符串不为空。

简短回答:

"undefined" !== undefined

请改为检查undefined

> var foo = { foo: 'foo' };
> foo['bar']
undefined
> typeof(foo['bar'])
"undefined"

另请注意,typeof(this.value[seperator] === "undefined")的意思是typeof(boolean),因为它首先计算您的表达式(this.value[seperator] === "undefined"),然后获取该表达式的类型。

你可能的意思是typeof(this.value[seperator]) === "undefined".

您的括号在此行中的错误位置:

if(typeof(this.value[seperator] === "undefined")){

您正在执行(this.value[seperator] === "undefined")的类型 - 这是一个布尔条件(将返回truefalse),所以我希望typeof给你"boolean".然后,您的if语句条件是字符串"boolean",由于它不是零长度,因此在 JavaScript 中被认为是 true。

你想要的是:

if((typeof this.value[seperator]) === "undefined") {