Check IF条件返回false,但IF中的语句仍然可以在JavaScript中工作

Check IF condition return false but the statement inside IF still work in JavaScript

本文关键字:IF 工作 JavaScript 返回 条件 false Check 语句      更新时间:2024-01-20

我有一个JavaScript,可以检查Object是否存在,如下所示,在.hamlc:中

假设@object1在这里不存在。

var property01;
// work as expected 
if (!#{@object1}) {
   console.log("not exist"); // print
} else {
   console.log("exist");
}

这正如预期的那样工作,并在控制台中显示文本"不存在",但有一种情况是,如果对象1确实存在,所以我想添加:

var property01;
if (!#{@object1}) { // should execute here and end the condition but not
   console.log("not exist"); // not print
   property01 = 'undefined';
} else {
   console.log("exist"); // not print as well
   property01 = '#{@object1.property01}'; // Delete this line will work normally but not what it should be.
}

上面给我返回了一个错误,说"无法读取未定义的属性‘property01’。

我这样做的原因是另一个应用了这个的页面可能在这里传递了@object1,所以这取决于应用的页面,但我只想让它工作,无论对象"@object1"是否存在。

我知道当前@object1是未定义的,因为它没有被传递。所以它应该只分配IF语句中声明的并且不涉及ELSE的"undefined"。这个有什么问题吗??

如果存在@object1,则分配给该property01,否则分配给undefined

var property01;
   property01 = (!#{@object1}) ? '#{@object1.property01} : undefined 

我认为您不小心将property01设置为字符串"undefined"。如果你想让你的脚本保持原样,只需删除第3行的引号:

if (!#{@object1}) { 
   console.log("not exist"); 
   property01 = undefined;
} else {
   console.log("exist");
   property01 = '#{@object1.property01}'; 

}