javascript 为什么我在 node.js 中使用 parseInt 会得到奇怪的结果?(与 chrome js 控制台不同的结果)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16880327/
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
Why am I getting weird result using parseInt in node.js? (different result from chrome js console)
提问by Renato Gama
I just noticed that:
我刚刚注意到:
//IN CHROME JS CONSOLE
parseInt("03010123"); //prints: 3010123
//IN NODE.JS
parseInt("03010123"); //prints: 790611
Since both are based on V8, why same operation yielding different results???
既然都是基于V8,为什么同样的操作会产生不同的结果???
回答by Adam Rackis
Undefined behavior occurs when the string being passed to parseInthas a leading 0, and you leave off the radix parameter.
当传递给parseInt的字符串有前导 0 时,会发生未定义的行为,并且您不使用 radix 参数。
An integer that represents the radix of the above mentioned string. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.
一个整数,表示上述字符串的基数。始终指定此参数以消除读者混淆并保证可预测的行为。当未指定基数时,不同的实现会产生不同的结果。
Some browsers default to base 8, and some to base 10. I'm not sure what the docs say about Node, but clearly it's assuming base 8, since 3010123
in base 8 is 790611
in base 10.
有些浏览器默认为 base 8,有些浏览器默认为 base 10。我不确定文档对 Node 的看法,但显然它假设 base 8,因为3010123
base 8 是790611
base 10。
You'll want to use:
你会想要使用:
parseInt("03010123", 10);