Program Tip

0.-5가 -5로 평가되는 이유는 무엇입니까?

programtip 2020. 11. 12. 20:07
반응형

0.-5가 -5로 평가되는 이유는 무엇입니까?


내가 쓰는 가정 0.5으로 0.-5예상치 못한 방법으로,하지만 여전히 실행할 수 있습니다. 무엇 않습니다 0.0.-5여전히 -5 실행하고 평가하여 수 있도록합니까?

나는 또한 시도 alert(0.-5+1)인쇄 -4, 자바 스크립트를 무시 않는 0.에서 0.-5?


a 뒤의 후행 숫자 .는 선택 사항입니다.

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

그래서

0.-5

평가하다

0 - 5

그것은 단지 -5입니다. 비슷하게,

0.-5+1

이다

0 - 5 + 1

그것은

-5 + 1

또는 -4.


0.-5성공적으로 파싱 할 수있다 0.[1] , -5. 다음은 AST 탐색기에서 생성 한 표현식에 대한 추상 구문 트리입니다.

AST 탐색기에서 생성 한 구문 분석 트리

이것은 (예기치 않은 방식으로) 유효한 JavaScript이며 -5.


[1] According to the grammar for numeric literals the decimal digits and exponent parts are optional:

NumericLiteral ::
  DecimalLiteral
  [...]

DecimalLiteral ::
  DecimalIntegerLiteral . DecimalDigitsopt ExponentPartopt


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
5 .toString() // awesome

See this question to find out why.


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?


console.log(0. - 5)      // -5
console.log(0 - 5)       // -5
console.log('0.' - 5)    // -5
console.log('0' - 5)     // -5
console.log(0.-5 === -5) // true

'0.' 또는 '0'은 유형이 숫자에 대해 고유하기 때문에 JavaScript에서 동일합니다. 빼기 연산자는 숫자 사이에 있으므로 항상 전달하는 것을 숫자로 변환하십시오. Python에서는 여러 유형이 있기 때문에 첫 번째는 Float이고 두 번째는 Integer입니다.

참고 URL : https://stackoverflow.com/questions/54859228/why-does-0-5-evaluate-to-5

반응형