Why does 0.-5 evaluate to -5?

问题: Suppose I write 0.5 as 0.-5 in unexpected way, but it can still run. What does 0. in 0.-5 do so that it can still run and evaluates to -5? I also tried alert(0.-5+1) whic...

问题:

Suppose I write 0.5 as 0.-5 in unexpected way, but it can still run. What does 0. in 0.-5 do so that it can still run and evaluates to -5?

I also tried alert(0.-5+1) which prints -4, does JavaScript ignore 0. in 0.-5?


回答1:

Trailing digits after a . are optional:

console.log(0. === 0);

So

0.-5

evalutes to

0 - 5

which is just -5. Similarly,

0.-5+1

is

0 - 5 + 1

which is

-5 + 1

or -4.


回答2:

In JS you can express a number with optional decimal point.

x = 5.;    //5
x = 5. + 6.   //11

And as of Tvde1's comment, any Number method can be applied too.

5..toString()

This syntax let us run the Number functions without parentheses.

5.toString() //error
(5).toString() //good
5..toString() //good

See this question to find out why.


回答3:

0.-5 could be successfully parsed as 0., - and 5. Below is the abstract syntax tree for the expression (by AST explorer):

Parse tree generated by AST explorer

This (in an unexpected way) is valid JavaScript and evaluates to -5.

PS: An abstract syntax tree could be used to answer questions, such as what does a+++b actually do.


回答4:

I would think that the real answer is not about the decimal point, but is about the minus sign: isn't that going to be interpreted as an operator if it is preceded by anything that looks like a number?

  • 发表于 2019-02-26 05:33
  • 阅读 ( 244 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除