为什么 javascript if 语句在给定字符串/数字(非零)输入时返回 true?



我是编码新手,我想知道为什么下面的语句给出了真值。谁能解释一下这个逻辑?
当给出数字输入时,如果条件测试它是否是数字,我认为它应该返回true而不是false。
谢谢你的帮助。

// Statement 1
if ("d") {
reply = "TRUE!";
} else {
reply = "FALSE?!";
}
console.log(reply)
// Returns "TRUE!"
// Statement 2
if (2) {
reply = "TRUE!";
} else {
reply = "FALSE?!";
}
console.log(reply)
// Also returns "TRUE!"
// Statement 3
if (0) {
reply = "TRUE!";
} else {
reply = "FALSE?!";
}
console.log(reply)
// Why does this return "FALSE?!"? I'm aware that 0 is false in boolean, but cannot understand how the syntax works considering statement 2.

非0、null、undefined、NaN或空字符串的输入将被判断为真

因为0是唯一等同于false的数字。除此之外,表述二等价于if(2==2)

最新更新