google chrome 控制台中的布尔逻辑解释

Boolean logic interpretation in google chrome console

我很难弄清楚为什么下面的代码不能按预期工作:

const userInput = prompt("Enter something");

if (userInput) {
    console.log("TRUTHY");
} else {
    console.log("FALSY");
}

无论我做什么,我总是得到“真相”。我理解这段代码的逻辑,即使 运行 来自 class 的源文件,我也没有得到预期的输出。

每当输入为:0、null、未定义、空字符串或 NaN 时,我应该得到“FALSY”。

我做错了什么? 谢谢。

编辑 1:事实证明我已经超前了。该代码实际上应该 return "TRUTHY" 除非您输入空字符串。


您使用的是哪个浏览器?因为当我 运行 这段代码在 ms edge 上时,当我什么都不输入时它 returns FALSY。另外,userInput默认设置为字符串类型,字符串“0”为真,因为它包含了一些东西。您必须使用 parseInt() 将值转换为整数,尽管这看起来不像您想做的那样。考虑查找语法错误,并检查您的浏览器是否是最新的。

由于 userInput 是一个字符串,我们必须检查它的长度以确定它是否为空

const userInput = prompt("Enter something");

if (userInput.length !== 0 && userInput == 0 && userInput == null && userInput == NaN) {
    console.log("TRUTHY");
} else {
    console.log("FALSY");
}

将 if() 更改为:

  if  (userInput == true) {
 

这是因为 if(),如您所说,执行严格相等 (===),所以对象类型非常匹配。