JavaScript 中的整数
MDN 指出:
JavaScript 中的数字是 “双精度 64 位格式 IEEE 754 值”,根据规范。 这有一些有趣的 结果。 没有这样的事情 JavaScript 中的整数,所以你有 小心一点 算术(如果您习惯用 C 进行数学计算) 或Java。
这表明所有数字都是float
。有没有办法使用int
egers,而不是float
?
MDN states:
Numbers in JavaScript are
"double-precision 64-bit format IEEE
754 values", according to the spec.
This has some interesting
consequences. 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.
This suggests all numbers are float
s. Is there any way to use int
egers, not float
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Javascript 中实际上只有几种数据类型:对象、数字和字符串。正如您所读到的,JS 数字都是 64 位浮点数。没有整数。
Firefox 4 将支持类型化数组,您可以在其中拥有真实整数数组,例如:https://developer.mozilla.org/en/JavaScript_typed_arrays
在那之前,有一些黑客方法可以将整数数组存储为字符串,并使用
charCodeAt()
取出每个整数。There are really only a few data types in Javascript: Objects, numbers, and strings. As you read, JS numbers are all 64-bit floats. There are no ints.
Firefox 4 will have support for Typed Arrays, where you can have arrays of real ints and such: https://developer.mozilla.org/en/JavaScript_typed_arrays
Until then, there are hackish ways to store integer arrays as strings, and plucking out each integers using
charCodeAt()
.我认为它永远不会支持整数。这不是问题,因为每个无符号 32 位整数都可以准确地表示为 64 位浮点数。
现代 JavaScript 引擎可能足够智能,可以在数字为整数时生成特殊代码(通过安全检查来确保这一点),但我不确定。
I don't think it ever will support integers. It isn't a problem as every unsigned 32 bit integer can be accurately represented as a 64 bit floating point number.
Modern JavaScript engines could be smart enough to generate special code when the numbers are integer (with safeguard checks to make sure of it), but I'm not sure.
使用这个:
你可以这样使用它:
Use this:
And yo can use it like this:
对整数的支持为零。每次需要时对变量进行四舍五入应该是一个简单的问题。性能开销一点也不差。
There is zero support for integers. It should be a simple matter of rounding off a variable every time you need it. The performance overhead isn't bad at all.
如果您确实需要使用整数,只需对遇到的每个数字使用向下取整方法即可。
除此之外,Javascript 的松散类型是它的优势之一。
If you really need to use integers, just use the floor method on each number you encounter.
Other than that, the loose typing of Javascript is one of it's strengths.