字符串强制转换为布尔值

时间:2017-08-09 13:48:01

标签: javascript coercion

Boolean("a")

在浏览器控制台中返回true 那么为什么

"a" == true

返回false?

3 个答案:

答案 0 :(得分:0)

您需要了解Javascripts的工作原理。

"a"是一个字符串。 true是一个布尔值。

因此"a"不等于true

Boolean("a"),想问“是"a"?”。这个奇怪的问题将回答true如果你输入的内容(所以这里"a")是[隐式地不是空的或空的]。

您不应在此上下文中使用此Boolean函数,结果永远不会是您的想法(Boolean("false")将返回true例如)

有关详细信息,请参阅此处:https://stackoverflow.com/a/264037/6532640

答案 1 :(得分:0)

// Boolean("a") is equal to asking if "a" == "a" so it will return true
console.log(Boolean("a"));

// "a" == true can't return true, because a string and a boolean can't be equal
console.log("a" == true);

// for the same reason this will return false too
console.log("true" == true);

// and this will return true
console.log("true" == true.toString());

//-----------------------------------------

// If we talk about numbers, there are different rules.
// In javascript you will be able to convert a string with 
// numbers to a number and vice versa 

// this is why "1" is equal to 1
console.log("1" == 1);

// considering the interest in trying to use every kind of
// variable in var, they described some basical rules
// for example adding a number to a string will work
// like every language

// this is why here you will obtain "11" as result
var one = "1";
console.log(one+1);

// in this case - doesn't work with strings, so our var one
// will be considered as an integer and the result will be 1
var one = "1";
console.log(one-1+1);

答案 2 :(得分:0)

==中如何定义某些类型的NaN运算符函数。如下:

  

7.2.13抽象平等比较

     

比较x == y,其中x和y是值,产生true或false。这样的比较如下进行:

     
      
  1. 如果Type(x)与Type(y)相同,那么   返回执行Strict Equality Comparison x === y。
  2. 的结果   
  3. 如果x为null且y未定义,则返回true。
  4.   
  5. 如果x未定义且y为null,则返回true。
  6.   
  7. 如果Type(x)为Number且Type(y)为String,则返回比较结果x ==! ToNumber(Y)。
  8.   
  9. 如果Type(x)是String而Type(y)是Number,则返回比较结果! ToNumber(x)== y。
  10.   
  11. 如果Type(x)是布尔值,则返回比较结果! ToNumber(x)== y。
  12.   
  13. 如果Type(y)是布尔值,则返回比较结果x ==! ToNumber(Y)。
  14.   
  15. 如果Type(x)是String,Number或Symbol而Type(y)是Object,则返回比较结果x == ToPrimitive(y)。
  16.   
  17. 如果Type(x)是Object而Type(y)是String,Number或Symbol,则返回比较结果ToPrimitive(x)== y。
  18.   
  19. 返回false。
  20.   

现在我们可以将它们应用于上述情况。首先将布尔值转换为数字,然后尝试将字符串转换为数字(解析为"a" == true // Case 7 (true --> 1) // =>"a" == 1 // Case 5 ("a" --> NaN) // => NaN == 1 => false ):

2> /dev/null