JavaScript truthiness in boolean to numbers comparison

前端 未结 3 1773
别跟我提以往
别跟我提以往 2020-12-10 18:49

I\'m new to JavaScript and I\'m trying to learn it from internet resources. While I\'m aware that there will plenty of cr*p material, one thing most people seemed to agree i

3条回答
  •  感动是毒
    2020-12-10 19:37

    With non-strict comparison (==) if the operands are not of the same type, they will be casted/coerced and strictly compared, with first preference being to numbers if either operand is a number or boolean (MDN).

    So true == 2 evaluates to Number(true) === 2 which is 1 === 2, which is false.

    Of course you can always force things to compare as you want them to, which is explicit and can solve hard-to-find problems later on:

    true === Boolean(2) is true.

提交回复
热议问题