parseInt("010",10);与parseInt(010,10); [英] parseInt("010", 10); vs. parseInt(010, 10);

查看:69
本文介绍了parseInt("010",10);与parseInt(010,10);的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 parseInt 的特定结果感到困惑.我以为我了解它的大多数怪癖,但这还不清楚.

I'm confused about a particular result of parseInt. I thought I understood most of its quirks, but this one is unclear.

parseInt("010", 10); // 10

parseInt(010, 10);   // 8, but expecting 10

在第二个示例中,我指定了正确的基数.产生意外结果的原因是什么?

In the second example I specified the correct radix. What's the reason for the unexpected result?

解决方案

问题在于八进制文字.当数字以0开头时,它被视为八进制文字.

The problem is with octal literal. When a number is prepended with 0, it's seen an as octal literal.

如果执行

console(010); // 8

在非脚本模式下,您将获得8.parseInt具有我认为是奇怪行为的原因是因为我实际上是在执行

in non-script mode, you will get 8. The reason that parseInt is having what I thought was strange behavior was because I was essentially executing

parseInt(8, 10); // 8

,预计为10.

ParseInt从来没有看到010,只有8.感谢大家的帮助.

ParseInt never saw 010, only 8. Thanks to everyone for helping out.

推荐答案

该数字在传递给 parseInt 之前已被解析.

The number is being parsed before being passed to parseInt.

例如,这类似于它的工作方式:

For example, it's similar to how this works:

var x = 010;
console.log(x); // 8
parseInt(x, 10); 

由于您要传递8,所以您当然会获得8.在数字前加0将使它成为一个八进制文字,使用8的底数.您可以删除前导0(首先使前导0毫无意义),或者(如您所做的那样)在您的问题中)将其作为字符串传递.

Since you're passing 8 in, of course you're going to get 8 back. Prepending a number with 0 will make it an octal literal, which is using a base of 8. You can either remove the leading 0 (having the leading 0 there doesn't really make sense in the first place), or (as you did in your question) pass it as a string.

请注意,并非所有浏览器都可以这样做,只是与以前的代码兼容的浏览器(不是必需的),以及

Note that not all browsers do this, it is simply ones that are compatible with previous code that do this (it's not required), and implementations must not parse octal literals in ES5 strict mode. To see this in effect, compare the non-strict version:

(function ()
{   // not strict
    parseInt(010, 10);
})();

...返回8或10(取决于实现),并带有严格的版本:

... which returns either 8 or 10 (depending on the implementation), with the strict version:

(function ()
{   "use strict";
    parseInt(010, 10);
})();

这将导致 SyntaxError:严格模式下不允许使用八进制文字..

这篇关于parseInt("010",10);与parseInt(010,10);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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