为什么我在 node.js 中使用 parseInt 会得到奇怪的结果?(与 chrome js 控制台的结果不同) [英] Why am I getting weird result using parseInt in node.js? (different result from chrome js console)

查看:46
本文介绍了为什么我在 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 为基数的 3010123790611 以 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);

这篇关于为什么我在 node.js 中使用 parseInt 会得到奇怪的结果?(与 chrome js 控制台的结果不同)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆