为什么eval(“475957E

编程入门 行业动态 更新时间:2024-10-14 10:44:25
为什么eval(“475957E-8905”)==“475957E-8905”是真的?(Why eval(“475957E-8905”) == “475957E-8905” is true?)

我用nodeJs制作了一个程序,可以生成如下代码

eval("XXXXXX") == "XXXXXX"

它工作得很好,但是他立刻给了我这个:

eval("475957E-8905") == "475957E-8905"

我用Firebug对它进行了测试,结果是true 。但我不明白为什么。

当然, eval("475957E-8905")返回0但为什么0 == "475957E-8905" ?

I made a program with nodeJs which generate code such as

eval("XXXXXX") == "XXXXXX"

It's working pretty well, but at a moment he gave me this :

eval("475957E-8905") == "475957E-8905"

I tested it with Firebug, and the result is true .But I don't really understand why.

Of course, eval("475957E-8905") return 0 but why 0 == "475957E-8905" ?

最满意答案

这个难题有两个部分:浮点数和使用==类型不敏感比较。

首先, 475957E-8905评估为浮点数475957 * 10 ^ -8905 ,这是令人难以置信的小; 在浮点方面,由于javascript的精度限制,它与0相同。 所以, eval("475957E-8905")返回0 。

现在,为拼图的第二部分。

==表示类型不必匹配,所以nodejs(就像任​​何JavaScript引擎)试图转换其中的一个,以便它们可以比较它们。

由于eval("475957E-8905")返回0 ,因此它会尝试将"475957E-8905"转换为整数。 正如我们所见,那也是0 。 因此,比较结果为0 == 0 ,这是正确的。

请注意,如果您执行eval("3") == "3"或eval("3") == 3 ,则会发生同样的情况 - 在每种情况下,都将字符串转换为数字并进行比较。

避免这个问题

你可以像这样强制类型敏感的比较:

eval("475957E-8905") === "475957E-8905"

它返回false,因为===告诉javascript引擎只有在类型和值都匹配时才返回true。

There are two pieces to this puzzle: floating-point numbers and type-insensitive comparison using ==.

First, 475957E-8905 evaluates as the floating point number 475957 * 10 ^ -8905, which is incredibly small; in floating-point terms, it's the same as 0 due to the precision limitations of javascript. So, eval("475957E-8905") returns 0.

Now, for the second piece of the puzzle.

The == means that the types don't have to match, so nodejs (like any JavaScript engine) tries to convert one of them so it can compare them.

Since eval("475957E-8905") returned 0, it tries to convert "475957E-8905" to an integer as well. As we have seen, that is also 0. Thus, the comparison is 0 == 0, which is true.

Note that the same thing happens if you do eval("3") == "3" or eval("3") == 3 -- in each case, the strings are converted to numbers and compared.

Avoiding this problem

You can force a type-sensitive comparison like this:

eval("475957E-8905") === "475957E-8905"

which returns false, because the === tells the javascript engine to return true only if the types and the values both match.

更多推荐

本文发布于:2023-08-07 17:04:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465372.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:eval

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!