【问题标题】:Is there a more efficient way to do this without all the "if" and "else" statements?没有所有“if”和“else”语句,有没有更有效的方法来做到这一点?
【发布时间】:2013-06-02 11:34:20
【问题描述】:

您将如何更有效地进行编程?

if( randomYear%4==0 ) { 
    if( randomYear%100==0 ) {
        if( randomYear%400==0 ) {
            randomDay = 1 + Math.floor(Math.random()*29);
        }
        else {
            randomDay = 1 + Math.floor(Math.random()*28);
        }
    else{
        randomDay = 1 + Math.floor(Math.random()*29);
    }
else{
    randomDay = 1 + Math.floor(Math.random()*28);
}

首先,我使用的是 math.floor,因为它包含 0 并且不包含 1,这正是我要寻找的。这样做的目的是确定变量 'randomYear' 是否是闰年并且在二月有适当的日子。

我主要关心所有 if 和 else 语句。顺便说一句,我正在使用 Javascript。 非常感谢!!

【问题讨论】:

  • 使用 Date 类型,它会为您完成所有这些工作。
  • 您也可以将1 + Math.floor()替换为Math.ceil()
  • @jcsanyi - 不,你不能:Math.random() 可能返回0
  • @nnnnnn - 你是对的。谢谢。

标签: javascript performance if-statement


【解决方案1】:

你甚至不需要数学:

var tmp = new Date(year,1,29); // attempt to get February 29th
isleapyear = (tmp.getMonth() == 1);

【讨论】:

  • 这对我来说似乎是众所周知的“正确的做法”。在给定年份的 2 月初 29 天后创建一个日期,然后找出生成的日期是否仍然在 2 月份是一个很好的解决方案,它依赖于 JavaScript 已经“知道”大量关于闰年、时区等等等等。
【解决方案2】:

这个怎么样?

var maxDays = 28;
if (randomYear%4 == 0 && (randomYear%100 != 0 || randomYear%400 == 0)) {
    maxDays = 29;
}
randomDay = 1 + Math.floor(Math.random() * maxDays);

【讨论】:

  • +1。或其他选项:var maxDays = (randomYear%4 == 0 && (randomYear%100 != 0 || randomYear%400 == 0)) ? 29 : 28;
  • 如果你打算这样做,为什么不全力以赴:randomDay = 1 + Math.floor(Math.random() * ((randomYear%4 == 0 && (randomYear%100 != 0 || randomYear%400 == 0)) ? 29 : 28));
【解决方案3】:

如果您同意包含第三方库,请尝试使用此库:

http://momentjs.com/

你可以这样做:

moment([2000]).isLeapYear() 

检查 2000 年是否是闰年,然后你可以做适当的逻辑。您还可以使用其验证 api 检查是否存在某年的 2 月 29 日。

【讨论】:

    【解决方案4】:

    您可以按照以下方式进行操作。

    function isLeapYear(year){
      return !(year%400) || ((year%100 > 0) && !(year%4)) ;
    }
    
    function getRandomDay(year){
      return 1 + Math.floor(Math.random()* (isLeapYear(year)?29:28))
    }
    
    var day = getRandomDay(2000);
    

    就性能而言,它可能不会产生大的变化。但这是用更少的行数编写有组织的可重用代码的方法。

    【讨论】:

      猜你喜欢
      • 2014-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多