javascript 在javascript中将字符串“009”解析为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12750569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing the string "009" as integer in javascript?
提问by Baskar
how to parse 009in javascript i need return value as 9but it returns 0.
But when i parse 001 it returns 1.
如何在 javascript 中解析009我需要返回值为9但它返回 0。
但是当我解析001 时它返回 1。
var tenant_id_max = '3-009';
tenant_id_split = tenant_id_max.split("-");
var tenant_id_int = tenant_id_split[1];
var tenant_id_count = parseInt(tenant_id_int);
回答by Denys Séguret
Do
做
var tenant_id_count = parseInt(tenant_id_int, 10);
That's because a string starting with "0" is parsed as octal (which doesn't work very well for "009", hence the 0 you get) if you don't specify the radix.
那是因为如果您不指定基数,以“0”开头的字符串将被解析为八进制(这对于“009”来说效果不佳,因此会得到 0)。
From the MDN:
来自MDN:
If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.
如果输入字符串以“0”开头,则基数为八(八进制)。这个特性是非标准的,一些实现故意不支持它(而是使用基数 10)。由于这个原因,在使用 parseInt 时总是指定一个基数。
The most important thing to remember is Always specify the radix.
要记住的最重要的事情是始终指定基数。