4

如果我可以说:

var big = (x > 10) ? true : false;

代替:

var big;
if (x > 10) {
    big = true;
}
else {
    big = false;
}

我如何使这个同样更短?

var now = new Date

if (now.getHours() < 5) {
    return "late night pick me up";
}
else if (now.getHours() < 9) {
    return "breakfast";
}
else if (now.getHours() < 13) {
    return "lunch";
}
else if (now.getHours() < 17) {
    return "afternoon snak";
}
else {
    return "dinner";
}

非常感谢!

4

9 回答 9

9
var now = new Date().getHours();

return now < 5 ? "late night pick me up" :
       now < 9 ? "breakfast" :
       now < 13 ? "lunch" :
       now < 17 ? "afternoon snak" : "dinner";
于 2011-08-05T11:50:57.447 回答
4

你不能,没有一堆凌乱的嵌套三元运算符。三元运算符只适用于一个班轮。

于 2011-05-20T15:54:53.240 回答
3

你不能特别简写,我个人会这样写:

if (now.getHours() < 5) return "late night pick me up";
else if (now.getHours() < 9) return "breakfast";
else if (now.getHours() < 13) return "lunch";
else if (now.getHours() < 17) return "afternoon snak";
else return "dinner";

这还不算太糟糕吧?

于 2011-05-20T15:54:21.857 回答
3

您可能不想这样做,因为可以说它的可读性会降低。但是,您可以像这样简单地嵌套三元运算符:

var now = (now.getHours() < 5) ? "late night pick me up" : ((now.getHours() < 9) ? "breakfast" : ((now.getHours() < 13) ? "lunch" : ((now.getHours() < 17) ? "afternoon snack" : "dinner")))));

我希望你能明白为什么这不是一个好主意!

像这样更长、更复杂的条件通常需要多行和良好的块分隔才能轻松理解 - 虽然您可以添加换行符,但标准if-else块最终会在清楚地表达您的意图方面胜出。

于 2011-05-20T15:54:49.110 回答
2

首先,尝试var big = x > 10;代替var big = (x > 10) ? true : false;

其次,当你有回报时,你不需要 if-else。

//looks  a little confusing, but you can move the return to line after ifs
var now = new Date  
if (now.getHours() < 5)  return "late night pick me up"; 
if (now.getHours() < 9)  return "breakfast";
if (now.getHours() < 13) return "lunch";
if (now.getHours() < 17) return "afternoon snak";
return "dinner"; 
于 2011-05-20T16:05:55.060 回答
1

它看起来会很乱:

return ((now.getHours() < 5)?"late night pick me up":
         ((now.getHours() < 9)?"breakfast":
            ((now.getHours() < 13)?"lunch":
               ((now.getHours() < 17)?"afternoon snack":
                  "dinner"
               )
            )
          )
       );

你必须记住匹配括号。

于 2011-05-20T15:53:45.383 回答
1

你总是可以使用 switch 语句:

switch(true)
{
case (now.getHours() < 5):
  return "late night pick me up";
  break;
case (now.getHours() < 9):
  return "breakfast";
  break;  //etc...
default:
  return "dinner";
}
于 2011-05-20T15:53:58.003 回答
1

我偶然发现了这个以寻找其他东西。这是一个使用逻辑运算符并滥用事实字符串文字是真实的事实的速记技巧 =]

var hr = new Date().getHours();

return hr < 5 && 'late night pick me up' 
    || hr < 9 && 'breakfast' 
    || hr < 13 && 'lunch' 
    || hr < 17 && 'afternoon snack' 
    || 'dinner';
于 2012-09-08T06:32:43.967 回答
0

您始终可以使用表来复制功能:

var now = new Date();
var meals = [
    "late night pick me up",
    "breakfast",
    "lunch",
    "afernoon snack",
    "dinner"];
return meals[parseInt(now.getHours()-4)/4];
于 2011-05-20T15:57:23.520 回答