簡體   English   中英

if/else 調用函數,其余邏輯相同

[英]if/else to call the function, the rest of the logic is identical

我在 js 函數中有一個 js 代碼。 這包含一個包含相同功能的if else條件,唯一改變的是參數。

所以唯一不同的是你傳遞給函數的參數字符串。 if/else 用於調用函數,其余邏輯相同。

是否可以調用該函數,其余邏輯相同?

return $(this).each(function () {
                if (coffeeId == "showCoffeeId") {
                    var todayDate = NoteWorklist.getDateTime("appleTime");
                    value.Year = todayDate.getFullYear();
                    value.Month = todayDate.getMonth() + 1;
                    value.Day = todayDate.getDate();
                    value.today = todayDate;
                    value.inputDate = todayDate;
                } else {
                    var todayDate = NoteWorklist.getDateTime("orangeTime");
                    value.Year = todayDate.getFullYear();
                    value.Month = todayDate.getMonth() + 1;
                    value.Day = todayDate.getDate();
                    value.today = todayDate;
                    value.inputDate = todayDate;
                }
            });

只需使用三元運算符:

return $(this).each(function () {
       var todayDate = NoteWorklist.getDateTime(coffeeID == "showCoffeeId" ? "appleTime" : "orangeTime");
       value.Year = todayDate.getFullYear();
       value.Month = todayDate.getMonth() + 1;
       value.Day = todayDate.getDate();
       value.today = todayDate;
       value.inputDate = todayDate;
});

你當然可以:

return $(this).each(function () {

    var todayDate = NoteWorklist.getDateTime(coffeeId == "showCoffeeId" ? "appleTime" : "orangeTime");
    value.Year = todayDate.getFullYear();
    value.Month = todayDate.getMonth() + 1;
    value.Day = todayDate.getDate();
    value.today = todayDate;
    value.inputDate = todayDate;

});
    if (coffeeId == "showCoffeeId") {
       var todayDate = NoteWorklist.getDateTime("appleTime");
    } else {
      var todayDate = NoteWorklist.getDateTime("orangeTime");
    }

    value.Year = todayDate.getFullYear();
    value.Month = todayDate.getMonth() + 1;
    value.Day = todayDate.getDate();
    value.today = todayDate;
    value.inputDate = todayDate;

像這樣?

return $(this).each(function () {
      var word =""
      if (coffeeId == "showCoffeeId") {
           word = "appleTime";
      } else {
           word = "orangeTime";
      }
     var todayDate = NoteWorklist.getDateTime(word);
     value.Year = todayDate.getFullYear();
     value.Month = todayDate.getMonth() + 1;
     value.Day = todayDate.getDate();
     value.today = todayDate;
     value.inputDate = todayDate;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM