Javascript variable with leading zeroes

前端 未结 3 915
不思量自难忘°
不思量自难忘° 2020-12-21 00:44

Javascript behaves differently with values having leading zeroes. alert(b) - prints different value.

var a = 67116;
var b = 00015;
alert(a);
alert(b);
         


        
3条回答
  •  离开以前
    2020-12-21 01:20

    As the other answers said, the leading zeroes make the number an octal literal. The decimal representation of the octal "15" is "13".

    Note that there is no reason to use leading zeroes on number literals unless you really really want them to be interpreted as octals. I mean, don't use var b = 00015. If you're getting that value from user input, then it will be a string (i.e. "00015"), and you can convert to a decimal number with parseInt:

    var b = "00015"; // or var b = document.getElementById('some_input').value
    var numB = parseInt(b, 10); // 15
    

提交回复
热议问题