为什么在node.js中使用parseInt会得到奇怪的结果? (来自chrome js控制台的不同结果) [英] Why am I getting weird result using parseInt in node.js? (different result from chrome js console)
问题描述
我刚刚注意到:
//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???
推荐答案
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
是10底的790611
.
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);
这篇关于为什么在node.js中使用parseInt会得到奇怪的结果? (来自chrome js控制台的不同结果)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!