开发者

In JavaScript, eval(010) returns 8 [duplicate]

This question already has answers here: Number with leading zero in JavaScript 开发者_开发百科 (3 answers) Closed 5 years ago.

If I use the code:

string = '010';
write = eval(string);
document.write(write)

I get 8 written on the page. Why? This happens even if 010 isn't a string.


Because 010 is parsed as octal. Javascript treats a leading zero as indicating that the value is in base 8.

Similarly, 0x10 would give you 16, being parsed in hex.

If you want to parse a string using a specified base, use parseInt:

parseInt('010', 8); // returns 8.
parseInt('010',10); // returns 10.
parseInt('010',16); // returns 16.


Prefixing a number with an 0 means it's octal, i.e. base 8. Similar to prefixing with 0x for hexadecimal numbers (base 16).

Use the second argument of parseInt to force a base:

> parseInt('010')
8
> parseInt('010', 10)
10


If you'd like to output the string 010 to the document, you can wrap the value in quotation marks:

var octal = eval('"010"');
typeof octal; // "string"

If you want to parse an integer or understand octals, read the other answers.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜