简体   繁体   中英

Javascript output differs when number having leading zero

Why javascript is create confusion with following code?

var a = 10; //will return output 10
var b = 010; //will return output 8

010 is an octal representation of denary value 8.

If you don't know about numbers system, there are basically 4 ways you can represent numbers in programming

  • Binary (Base 2)
  • Octal (Base 8)
  • Decimal (Base 10)
  • Hexadecimal (Base 16)

Read more about number system here

If you want to represent a octal number in JavaScript, you put 0 in front on any values, if you want to represent a value in hexadecimal it can be achieved by putting 0x in front of any number.

For Example,

var a= 010;    //8 in decimal
var b= 0xF;     //15 in decimal

Learn more about number in JavaScript here

From the earliest versions of C (1978), a leading zero has been used to denote an octal literal .

This has carried over to C++, Java, and even Javascript.

Some more courageous languages (Python 3 for example) are moving to 0o for an octal literal, as these days the leading 0 notation seems to do more harm than good.

If number is leading with 0 the Javascript will in interpret as octal number. Never write a number with a leading zero (like 07). Some JavaScript versions interpret numbers as octal if they are written with a leading zero.

The issue is that you're using loose mode and in loose mode in most environments a leading 0 followed by a digit indicates a legacy octal literal. In octal, 010 (which is to say, `10 octal) is the number eight. Octal is base 8, so the rightmost digit is the "ones" column, the one just left of it is the "eights" column, the one just left of that is the "sixty-fours" (8 x 8) column, etc. (Just like in decimal, the rightmost column is the "ones," the next one to the left is the "tens," the next to the left is the "hundreds," etc.)

Octal  Decimal
------ -------
    0        0
    1        1
...
    7        7
   10        8
   11        9
   12       10
   13       11
   14       12
   15       13
   16       14
   17       15
   20       16
...

To fix it:

  1. Use strict mode ( "use strict"; at the top, and/or use modules which are strict by default), and

  2. Don't start a decimal literal with 0 . :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM