【问题标题】:Equating strings with true in if [duplicate]在 if [重复] 中将字符串等同于 true
【发布时间】:2018-08-11 10:47:44
【问题描述】:

可能我很困惑,但我无法理解这种愚蠢的情况。

if("true"){
  console.log("Above is true");
}
else{
  console.log("Above is false");
}

在上述情况下,控制台可以很好地打印Above is true。这完全有道理。但是当我在做的时候:

if("true" == true){
  console.log("Above is true");
}
else{
  console.log("Above is false");
}

我看到Above is false 正在控制台中打印。

我在这里使用了一个松散的相等运算符,即使在强制之后 true 将转换为 "true" 所以它应该打印 Above is true 但不是。我错过了什么?

【问题讨论】:

  • "true" 是字符串,true 是布尔值,所以它们不相等
  • @JayShankarGupta 但我在这里使用松散的相等运算符。就像0 == false 是真的但0 === false 不是。
  • 你刚刚提醒我为什么我不使用 javascript :)
  • @Striped 抱歉,我没看懂你的评论。
  • @void 他想说 any 字符串是真实的

标签: javascript


【解决方案1】:

“如果其中一个操作数是布尔值,则布尔操作数如果为真则转换为 1,如果为假则转换为 +0。”

true == "true"; //false
true == "1"; //true
false == "false"; //false
false == ""; //true
false == "0"; //true

Further readings on here.

【讨论】:

    【解决方案2】:

    查看这篇文章https://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/

    //EQUALITY CHECK...
    "true" == true; 
    //HOW IT WORKS...
    //boolean is converted using toNumber
    "true" == 1;
    //string is converted using toNumber
    NaN == 1; //false!
    

    【讨论】:

    • //string is converted using toNumber - 不... -> 11.9.3.7(11.9.3.5 未完成)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多