JavaScript中有没有整数类型?
Is there or isn't there an integer type in JavaScript?
我刚刚开始学习 Javascript,我立即被 Mozilla A re-introduction to JavaScript (JS tutorial).
中看似矛盾的陈述弄糊涂了
一只手:
"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."
另一方面(紧接该段之后):
"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."
和
"You can convert a string to an integer using the built-in parseInt()
function."
那么,JavaScript中有没有整数之类的东西?
啊,是的,这可能会让人很困惑。在Javascript中,变量的类型是隐式定义的。
函数 parseInt
不会简单地考虑小数点,结果类型将是 int。
更新:随着新的 ES2020 标准的发布,这个答案不再完全正确,请参阅 (from @Mathias Lykkegaard Lorenzen) 关于 BigInt
的详细信息。
JS中只有Number数据类型表示数字
内部实现为IEEE 754双精度浮点数。
这意味着 - 从技术上讲,没有表示整数的专用数据类型。
实际上,这意味着我们可以安全地仅使用上述标准可以安全表示的数字。它包括范围内的整数值:[-9007199254740991; 9007199254740991]
。这两个值都定义为常量:Number.MIN_SAFE_INTEGER
and Number.MAX_SAFE_INTEGER
相应地。
我应该提一下,实际上有一种叫做 BigInt
的类型,它代表一个真正的整数。
但是,因为它不能与 Number
一起使用并且通常只用于更大的数字是个好主意,所以我不建议这样做。
不过我认为值得一提。
var n = BigInt(1337);
console.log(typeof n); //prints "bigint"
我相信提问者已经找到了his/her答案。但是对于像我这样的其他人,您可以使用 Number.isInteger() 方法检查 整数 或 JavaScript 中的数字.
MDN
我刚刚开始学习 Javascript,我立即被 Mozilla A re-introduction to JavaScript (JS tutorial).
中看似矛盾的陈述弄糊涂了一只手:
"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."
另一方面(紧接该段之后):
"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."
和
"You can convert a string to an integer using the built-in parseInt() function."
那么,JavaScript中有没有整数之类的东西?
啊,是的,这可能会让人很困惑。在Javascript中,变量的类型是隐式定义的。
函数 parseInt
不会简单地考虑小数点,结果类型将是 int。
更新:随着新的 ES2020 标准的发布,这个答案不再完全正确,请参阅 BigInt
的详细信息。
JS中只有Number数据类型表示数字
内部实现为IEEE 754双精度浮点数。
这意味着 - 从技术上讲,没有表示整数的专用数据类型。
实际上,这意味着我们可以安全地仅使用上述标准可以安全表示的数字。它包括范围内的整数值:[-9007199254740991; 9007199254740991]
。这两个值都定义为常量:Number.MIN_SAFE_INTEGER
and Number.MAX_SAFE_INTEGER
相应地。
我应该提一下,实际上有一种叫做 BigInt
的类型,它代表一个真正的整数。
但是,因为它不能与 Number
一起使用并且通常只用于更大的数字是个好主意,所以我不建议这样做。
不过我认为值得一提。
var n = BigInt(1337);
console.log(typeof n); //prints "bigint"
我相信提问者已经找到了his/her答案。但是对于像我这样的其他人,您可以使用 Number.isInteger() 方法检查 整数 或 JavaScript 中的数字. MDN