将八进制值传递给新的数字函数
我做了类似的事情:
Number.prototype.foo = function () {
//code
}
// Octal number!
(013).foo();
但是检查 foo 函数内部,我得到 11 作为值...出了什么问题?
I've made something like :
Number.prototype.foo = function () {
//code
}
// Octal number!
(013).foo();
But inspecting this inside of foo function, I get 11 as value... What's wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您预计会发生什么?
JavaScript 将所有以零开头的整数视为八进制 [*],因此
013
的实际值确实是11
(十进制)。Number
类仅处理值,并且不会知道您最初传入的是八进制常量。[*] 包含数字 8 或 9 的整数有一个例外 - 因为这些数字在八进制中不合法,即使存在前导零,解析器也会隐式地将它们视为十进制。
What did you expect to happen?
Javascript treats all whole numbers that start with a zero as octal[*] so the actual value of
013
is indeed11
(decimal). TheNumber
class only deals in values, and won't know that you originally passed in an octal constant.[*] There's an exception for whole numbers containing the digits 8 or 9 - since those aren't legal in octal the parser will implicitly treat them as decimal even in the presence of a leading zero.
一旦八进制数被解释为数字,它就与十进制数没有什么不同。
013
与11
完全相同。一旦 JavaScript 发现它是一个数字,它就只是一个数字——它不记得它的“八进制”或“十进制”。An octal number is no different from a decimal number once it's been interpreted as a number.
013
is exactly the same as11
. Once JavaScript sees that it's a number, it's just a number - it doesn't remember its "octalness" or "decimalness".这并不是真正的问题,因为您可以轻松地将其转换回八进制表示形式:
数字以十进制格式返回,但据我所知,其数字运算不会有任何不同。另请注意,提供给 JavaScript 的所有八进制数都将立即以这种方式“转换”:
This isn't really a problem as you can convert it back to an octal representation easily:
Numbers are returned in decimal format, but the numerical operations on it won't be any different as far as I know. Note also that all octal numbers supplied to JavaScript will be immediately "converted" in this fashion: