最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

types - In javascript, why is the string "true", after coercion, still not equal to boolean true? - Stack Over

programmeradmin4浏览0评论

In javascript, String(true) == "true" evaluates to true, and Boolean("true") == true evaluates to true, so why does "true" == true evaluate to false?

In javascript, String(true) == "true" evaluates to true, and Boolean("true") == true evaluates to true, so why does "true" == true evaluate to false?

Share Improve this question asked Jul 3, 2017 at 19:56 DustyDusty 3,9812 gold badges30 silver badges42 bronze badges 9
  • 1 not following your logic...why should it? – blockhead Commented Jul 3, 2017 at 19:58
  • 3 Because JavaScript? – Heretic Monkey Commented Jul 3, 2017 at 19:58
  • 3 maybe you get confused using Boolean("true"), since Boolean("false") also returns true. – Ulysse BN Commented Jul 3, 2017 at 19:59
  • Per the Boolean docs at MDN: "If the value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false. If the DOM object document.all is passed as a parameter, the new boolean object also has an initial value of false. All other values, including any object or the string "false", create an object with an initial value of true." – j08691 Commented Jul 3, 2017 at 20:00
  • 1 Note, that you've thrown the result of the type coersion away. – Teemu Commented Jul 3, 2017 at 20:01
 |  Show 4 more ments

2 Answers 2

Reset to default 9

In "true" == true the coercion is to number. So this bees:

NaN == 1

... which is false.

The loose equality operands table on mozilla might be useful to check out.

Take a look to the MDN (Mozilla Developer Network). When we pare two operands of differents types, [the Abstract Equality Comparison Algorithm] will attempt to convert them to the same type before making the parison.

Finally, the answer is the following:

If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.

Then

When paring a number and a string, the string is converted to a number value. JavaScript attempts to convert the string numeric literal to a Number type value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearest Number type value.

So, finally, we pare Nan == 1 which is false as pointed by @trincot.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论