Javascript variable with leading zeroes

*爱你&永不变心* 提交于 2019-12-10 14:04:20

问题


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

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

I am more interested to know What conversion is applied here by javascript inside alert(b) ? (If i have them in double quotes. They work fine.)


回答1:


Since js is weakly typed it thinks

var b = 00015

is an octal number

see this question for solution




回答2:


A leading 0 makes the value an octal literal, so the value you put will be interpreted as a base 8 integer.

In other words, 015 will be equivalent to parseInt('15', 8).




回答3:


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


来源:https://stackoverflow.com/questions/17114258/javascript-variable-with-leading-zeroes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!