开发者

Strange Javascript Problem Involving split("/");

Okay, so using the following function:

function date_add(date, days)
{
  var dim = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31};
  console.log(date.split("/"));
  var date_arr = date.split("/");
  console.log(date_arr);
  ...
}

I get the following output at the console screen for date_add("12/08/1990", 1)

["12", "08", "1990"]
["2", "08", "1990"]

Spending an hour struggling with what could fix this weird problem, on a whim I changed my function to the following:

function date_add(date, days)
{
  var dim = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31};
  date = date.split("/");
  console.log(date);
  ...
}

Magically, the code works again. Now don't get me wrong, I'm ecstatic that it worked. I'm seriously concerned over why it worked, though, when the other didn't. More or less I'm just concerned with why the other didn't work. Does anyone have a good explanation?

Edit: Now they're both broken. >.>

For Tomas, here is the full function:

function date_add(date, days)
{
  var dim = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31};
  console.log(date);
  console.log(date.split("/"));
  date_arr = date.split("/");
  console.log(date)
  if (date_arr[0][0] = "0") date_arr[0] = date_arr[0][1];
  if (date_arr[1][0] = "0") date_arr[1] = date_arr[1][1];
  var month = parseInt(date_arr[0]);
  var day   = parseInt(date_arr[1]);
  var year  = parseInt(date_arr[2]);
  console.log(month);
  console.log(day);
  console.log(year);

  if ((year%4 == 0 && year%100 != 0) || year%400 == 0)
    dim[2] = 29;

  day += days;
  while (day < 1)
  {
    month--;
    if (month < 1)
    {
      month = 12;
      year--;
    }
    day += dim[month];
  }

  while (dim[month] &开发者_运维知识库lt; day)
  {
    day -= (dim[month]+1);
    month++;
    if (month > 12)
    {
      month = 0;
      year++;
    }
  }

  return ""+month+"/"+day+"/"+year;
}

As for the input for the function, I called this function from the console using date_add('12/08/1990',1);


The problem with your original code is most probably you were not using the second parameter for your parseInt() calls, which is to specify the base for which you want to convert to, by default it assumes a 10 base, but when the number starts with zero as in your 08 case, then it assumes its an octal number, so the solution is to use the second parameter in your parseInt calls, like this:

var month = parseInt(date_arr[0], 10);
var day   = parseInt(date_arr[1], 10);
var year  = parseInt(date_arr[2], 10);

This behaviour have been fixed in last versions of javascript (EcmaScript 5), see this question for more info:

How do I work around JavaScript's parseInt octal behavior?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜