问题
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?
回答1:
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 indeed 11
(decimal). The Number
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.
回答2:
An octal number is no different from a decimal number once it's been interpreted as a number.
013
is exactly the same as 11
. Once JavaScript sees that it's a number, it's just a number - it doesn't remember its "octalness" or "decimalness".
回答3:
This isn't really a problem as you can convert it back to an octal representation easily:
var dec = 11;
alert(dec.toString(8)); // returns "13"
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:
alert(013); // returns 11
来源:https://stackoverflow.com/questions/6455014/passing-octal-value-to-new-number-function