判断揭秘

参考文章:《Truth, Equality and JavaScript》
《JavaScript 中的相等性判断》

也许你运行代码时会感到困惑,为什么字符串可以作为判断条件,字符串和true 进行 运算结果会是true

if ("potato") {
    console.log("potato" == false); //false
    console.log("potato" == true); //false
}

在JavaScript中,所有的条件语句和操作符遵循相同的强制转换规范。 比如说if(Expression)语句将使用抽象方法ToBoolean将表达式求值的结果强制为布尔值,为此,ES5规范定义了以下算法:

Argument Type Result
Undefined false
Null false
Boolean The result equals the input argument (no conversion).
Number The result is false if the argument is +0, −0, or NaN;otherwise the result is true.
String The result is false if the argument is the empty String (its length is zero);otherwise the result is true.
Object true

所以 "potato" 作为表达式 转换结果将是 true

==那么 "potato" == false是怎么进行运算的,如果"potato" == 1呢?==

运算规则如下:

Type(x) Type(y) Result
x and y are the same type See Strict Equality (===) Algorithm
null Undefined true
Undefined null true
Number String x == toNumber(y)
String Number toNumber(x) == y
Boolean (any) toNumber(x) == y
(any) Boolean x == toNumber(y)
String or Number Object x == toPrimitive(y)
Object String or Number toPrimitive(x) == y
otherwise… false

那么toNumber ,toPrimitive 是按照什么规则进行转换的

ToNumber

Argument Type Result
Undefined NaN
Null +0
Boolean The result is 1 if the argument is true.The result is +0 if the argument is false.
Number The result equals the input argument (no conversion).
String In effect evaluates Number(string);“abc” -> NaN;“123” -> 123
Object Apply the following steps:1. Let primValue be ToPrimitive(input argument, hint Number).2. Return ToNumber(primValue).

ToPrimitive

Argument Type Result
Object (in the case of equality operator coercion) if valueOf returns a primitive, return it. Otherwise if toString returns a primitive return it. Otherwise throw an error
otherwise… The result equals the input argument (no conversion).

你可能感兴趣的:(判断揭秘)