为什么我在 node.js 中使用 parseInt 会得到奇怪的结果?(与 chrome js 控制台的结果不同)
我刚刚注意到:
//IN CHROME JS CONSOLE
parseInt("03010123"); //prints: 3010123
//IN NODE.JS
parseInt("03010123"); //prints: 790611
既然都是基于V8,为什么同样的操作会产生不同的结果???
Since both are based on V8, why same operation yielding different results???
推荐答案
将字符串传递给 parseInt 有一个前导 0,并且您省略了 radix 参数.
Undefined behavior occurs when the string being passed to parseInt has a leading 0, and you leave off the radix parameter.
一个整数,表示上述字符串的基数.始终指定此参数以消除读者混淆并保证可预测的行为.当未指定基数时,不同的实现会产生不同的结果.
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.
有些浏览器默认以 8 为基数,有些以 10 为基数.我不确定文档对 Node 的看法,但显然它假设以 8 为基数,因为以 8 为基数的 3010123
是 790611
以 10 为底.
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.
你会想要使用:
parseInt("03010123", 10);
相关文章