The behavior of javascript is not always your expected
24 Oct 2009Let's raise the issue '07 + 08 = 07' firstly from this guy's article.
var a = '07'; var b = '08' alert(a + b); //'0708';
OK. We knew the result. What we will do is using the 'parseInt' method.
var a = '07'; var b = '08' alert(parseInt(a) + parseInt(b)); //'07';
The result is not our expected this time.
So boys give a lot of solutions. solution 1:
var a = '07'; var b = '08' alert(parseInt(a, 10) + parseInt(b, 10)); //'15';
solution 2:
var a = '07'; var b = '08' alert(Number(a) + Number(b)); //'15';
I like this solution. If the variable is a number, transform it to 'Number' directly to keep it safe. If the variable is a string, transform it to 'String' directly. The same issue occurred in Date function too.
var d = new Date(2009, 08, 02); //It's 2nd of JULY
The reason.
year Integer value representing the year. For compatibility (in order to avoid the Y2K problem), you should always specify the year in full; use 1998, rather than 98. month Integer value representing the month, beginning with 0 for January to 11 for December. date Integer value representing the day of the month (1-31).