Is there or isn't there an integer type in JavaScript?

左心房为你撑大大i 提交于 2020-01-28 19:39:41

问题


I am just starting to learn Javascript and I immediately got confused by seemingly contradictory statements in Mozilla's A re-introduction to JavaScript (JS tutorial).

One one hand:

"There's no such thing as an integer in JavaScript, so you have to be a little careful with your arithmetic if you're used to math in C or Java."

On the other hand (immediately after that paragraph):

"In practice, integer values are treated as 32-bit ints (and are stored that way in some browser implementations), which can be important for bit-wise operations."

and

"You can convert a string to an integer using the built-in parseInt() function."

So, is there such thing as integer in JavaScript or isn't there?


回答1:


There is only the Number data type in JS that represents numbers.

Internally it is implemented as IEEE 754 double precision floating point number.

What it means is that - technically there is no dedicated data type that represents integer numbers.

Practically it means that we can safely use only numbers that are safely representable by the aforementioned standard. And it includes integer values in the range: [-9007199254740991; 9007199254740991]. Both values are defined as constants: Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER correspondingly.




回答2:


I should mention that there is actually a type called BigInt which represents a true integer.

However, because it can't be used with Number and is generally only a good idea to use for larger numbers, I wouldn't advise it.

I thought it was worth a mention though.




回答3:


I believe questioner has already found his/her answer. But for others like me, you can check number is integer or not in JavaScript by using Number.isInteger() method. MDN




回答4:


Ah yes, this can be quite confusing. In Javascript, the type of a variable is implicitly defined.

the function parseInt will simply not take the decimal point into account and the type of the result would be an int.



来源:https://stackoverflow.com/questions/33773296/is-there-or-isnt-there-an-integer-type-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!