Domanda

can someone tell me why this var val="08"; alert(parseInt(val-1)); shows 7 but var val="08"; alert(parseInt(val)-1); shows -1 ?

Thnx

È stato utile?

Soluzione

parseInt("08") will give you NaN if the engine you're using extends parseInt to recognize octal (the leading 0 means "octal"). It will give you 8 if the engine follows the standard, which says not to do that (as of ES5).

parseInt("08"-1) is a bit redundant, because the expression "08"-1 will result in a number (which then gets passed into parseInt); just "08"-1 is all you need. Here's how that breaks down:

  • The engine processes the expression "08" - 1 by trying to turn "08" into a number. On an engine that extends numeric literal syntax to include octal, that would fail, but on engines that don't, it will give you 8. So the result of the expression is the number 7 (8 - 1).

  • The engine then does parseInt(7), which is redundant, as 7 is already a number. What happens is that 7 is turned into "7" and then parsed back into 7.

Note the difference above: The result of parseInt("08") - 1 will vary based on whether the engine extends what parseInt will parse, but the result of "08" - 1 will vary based on whether the engine extends numeric literal syntax. Those are two different things, and the ES5 specification does not allow engines to extend parseInt's syntax, but does allow them to extend numeric literal syntax (see §B.1.1), but only in loose mode. (Confusing, I know.)

The take-away message: Always use a radix with parseInt to tell it what number base to use.

Altri suggerimenti

Always use parseInt(val,10); to ensure that value is parsed in decimal system. In your case when you alert val-1 i.e. 08-1 so it is 7 i.e. parseInt(7) ==> 7

but when you do

parseInt(val)-1  ==> parseInt("08")-1 ==> 0-1 ==> -1

why it becomes 0 ? The answer is it assumes you want to parse in Octal number system.

So always use the second argument i.e. parseInt(whatevervalue,10);

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top