字符串强制转换为布尔值

String coercion into boolean

Boolean("a")

returns 在浏览器控制台中为真。
那么为什么

"a" == true

returns假的?

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

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

所以"a"不等于true.

Boolean("a"),如问"Is "a" ?"。这个奇怪的问题将回答 true 如果你输入的内容(所以这里 "a")是 [隐含的不是 null 或空的东西]。

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

查看此处了解更多信息:

// 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);

== 运算符如何在某些类型上运行在 ECMAScript specifications 中定义。如下:

7.2.13 Abstract Equality Comparison

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  1. If Type(x) is the same as Type(y), then Return the result of performing Strict Equality Comparison x === y.
  2. If x is null and y is undefined, return true.
  3. If x is undefined and y is null, return true.
  4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ! ToNumber(y).
  5. If Type(x) is String and Type(y) is Number, return the result of the comparison ! ToNumber(x) == y.
  6. If Type(x) is Boolean, return the result of the comparison ! ToNumber(x) == y.
  7. If Type(y) is Boolean, return the result of the comparison x == ! ToNumber(y).
  8. If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
  9. If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.
  10. Return false.

现在我们可以将它们应用于上述情况。首先将布尔值转换为数字,然后尝试将字符串转换为数字(解析为 NaN):

"a" == true
// Case 7 (true --> 1)
// =>"a" == 1
// Case 5 ("a" --> NaN)
// => NaN == 1
=> false