2

为我对 jQuery 的基本理解致歉。我正在尝试编写一个函数,该函数可以由用户设置值或留空,自行设置。它看起来像这样:

// Calendar
function eventCalendar(yearSet, monthSet) { 

    // Get current date
    var date = new Date();

    // Check to see if variables were set in function

    // Year
    if ((yearSet.length > 0)) {
            var year = yearSet;
        } else {
            var year  = date.getFullYear();
        }

    // Month
    if ((monthSet.length > 0)) {
            var month = monthSet;
        } else {
            var month = date.getMonth();
        }

    console.log(month + ', ' + year);   
}

但是,当函数在没有变量的情况下调用时,控制台会向我发送错误:

'yearSet 未定义'

我该如何解决这个问题?

4

5 回答 5

1

您可以检查参数的真实性或虚假性,而不是检查它们是否明确未定义:

function eventCalendar(yearSet, monthSet) { 
  var date = new Date();
  var year = yearSet && yearSet.length ? yearSet : date.getFullYear();
  var month = monthSet && monthSet.length ? monthSet : date.getMonth();
  console.log(month + ', ' + year);   
}

仅供参考,您当前的错误是由尝试访问变量 ( ) 的属性 ( length) 引起的。我建议让谷歌了解 JavaScript IMO 中的真实性和虚假性,这是该语言的一个非常有用的特性。undefinedyear

于 2012-06-18T15:40:15.253 回答
1
if(yearSet && yearSet.length) {
   //..
}

您可以像这样简化您的方法。

function eventCalendar(yearSet, monthSet) { 
  var date = new Date();
  //if yearSet is present it will get that or else from new Date
  var year = yearSet || date.getFullYear();
  //if monthSet is present it will get that or else from new Date
  var month = monthSet || date.getMonth();

  console.log(month + ', ' + year);   
}
于 2012-06-18T15:42:05.780 回答
0

将其与undefinednull代替检查长度进行比较

于 2012-06-18T15:38:04.440 回答
0

使用以下代码检查变量是否未定义:

if(typeof(variable) === 'undefined') {
    // var is undefined
}

您的代码会抛出错误,因为当您使用.length时假设给定变量存在。

于 2012-06-18T15:41:14.347 回答
0

还要考虑“”被认为是要包含的字段的有效值。你想做一些更性感的事情:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function eventCalendar (y,m) {
  var date = new Date(); 
  y=(isNumber(y) ? y : date.getFullYear(); 
  m=(isNumber(m) ? m : date.getMonth(); 
  console.log(m + " " + y);
}

未经测试,但它应该做你想做的事。

于 2012-06-18T15:43:48.030 回答