开发者

Passing octal value to new number function

I've made something like :

Number.prototype.foo = 开发者_如何学JAVAfunction () {
    //code
}

// Octal number!
(013).foo();

But inspecting this inside of foo function, I get 11 as value... What's wrong?


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.


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".


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜