简体   繁体   English

javascript正确与错误

[英]javascript true and false

i already know the following behavior, but can someone tell me WHY this happens? 我已经知道以下行为,但是有人可以告诉我为什么会这样吗? Thanks. 谢谢。

if("hello"==true)alert("it's true!"); //-> does not fire the alert
if("hello"==false)alert("it's true!"); //-> does not fire the alert
if("hello")alert("it's true!"); //-> fires the alert

In the first two, you're explicitly comparing a string to the boolean constants, and the string is obviously not equal to either. 在前两个中,您将显式地将字符串与布尔常量进行比较,并且该字符串显然不等于任何一个。 In the third line, you're testing the "truthiness" of the string, and any non-empty string evaluates to true in that context. 在第三行中,您正在测试字符串的“真实性”,并且任何非空字符串在该上下文中的评估结果均为true

In a comparison between a string and a boolean, the Abstract Equality Comparison Algorithm dictates that the comparison should be carried out as a numeric comparison. 在字符串和布尔值之间的比较中, 抽象相等比较算法指示该比较应作为数字比较进行。 Thus true is converted to 1 and false to 0; 因此, true转换为1, false转换为0; "hello" will be NaN . "hello"将是NaN NaN is never == to anything. NaN永远不会==任何事物。

true and false are boolean values and you are trying to compare boolean with string value hence you are facing the issue since the condition is not satisfied. truefalse是布尔值,并且您试图将布尔值与字符串值进行比较,因此由于条件不满足而面临问题。

In the third case you are not comparing you are simply making a check of true 在第三种情况下,您没有进行比较,只是检查了true

You can't compare string ("HELLO") with boolean (true). 您无法将字符串(“ HELLO”)与布尔值(true)进行比较。 They are 2 different types. 它们是2种不同的类型。 The last alert triggers because you aren't comparing it to anything. 最后一个警报将触发,因为您没有将它与任何事物进行比较。 It will only returned if you will test empty string 仅当您测试空字符串时才会返回

var foo = "Hello world!"; 
if(foo){ 
  //if foo is not empty 
}else{ 
  //if foo is empty
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM