Console.log output in javascript

后端 未结 6 584
闹比i
闹比i 2021-01-01 01:22

Why do console.log(00); and console.log(01); print 0 & 1 in the browser console and not 00 & 01?

console.log(00); // prints         


        
6条回答
  •  北荒
    北荒 (楼主)
    2021-01-01 01:28

    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.

    That is because JavaScript treats leading 0 as octal number and that is why you are getting the octal number(base 8).

    You could use parseInt with radix to eliminate these kind of issues.

    And the reason why console.log treats the input as octal is, by default console.log calls valueOf method of input. If it doesn't returns anything it will call toString method.

    And the valueOf method returns values like below:

    00.valueOf()   // 0
    01.valueOf()   // 1
    011.valueOf()  // 9
    0111.valueOf() // 73
    

    Reference:- http://javascript.info/tutorial/object-conversion

    For your reference I've added the number system table

    Number System table

提交回复
热议问题