Javascript - Leading zero to a number converting the number to some different number. not getting why this happening?

前端 未结 2 1480
無奈伤痛
無奈伤痛 2020-12-06 20:57

A leading zero to some number converting the number to some unknown number format. for example :

017 is getting converted to 15

相关标签:
2条回答
  • 2020-12-06 21:21

    If there is a leading 0, it is converting it to octal (base 8) as long as its a valid number in base 8 (no numbers greater than 7).

    For example:

    017 in base 8 is 1 * 8 + 7 = 15 037 in base 8 is 3 * 8 + 7 = 31

    018 is converted to 18 because 018 isn't a valid number in base 8

    Note that the behavior as to which base the number is converted to by default can be browser-specific, so its important to always specify the base/radix when using parseInt:

    parseInt("017",10) === 17

    UPDATE based on comments:

    parseInt expects a string as the first argument, so

    parseInt("012",10) === 12

    0 讨论(0)
  • 2020-12-06 21:41

    One of the reasons to "use strict";

    (function() {"use strict"; 017})()
    
    // Firefox => SyntaxError: "0"-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the \"0o\" prefix instead 
    // Chrome, Node => SyntaxError: Octal literals are not allowed in strict mode.
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_octal

    0 讨论(0)
提交回复
热议问题