2017-03-15 53 views
0

我翻看了有關該主題的其他問題,沒有任何內容專門針對我的主題。返回最佳做法後,發出Javascript警告無法訪問的代碼

有沒有反對使用這種類型的代碼的規則。我覺得在這種情況下,使用else if是無用的,因爲每個if都有一個return語句。

var __sortBySortType = function(x, y, index, type) { 
    if (type === "name") { 
     x[0]["sortname"] = x[0]["sortname"] || x[0]["name"]; 
     y[0]["sortname"] = y[0]["sortname"] || y[0]["name"]; 
     type = "sortname"; 
    } 
    if (typeof global !== "undefined" && typeof global.locale !== "undefined" && global.locale.compareString !== "undefined" && index === 0) { 
     return sim.locale.compareString(x[index][type], y[index][type]); 
    } 
    if (x[index][type] > y[index][type]) { 
     return 1; 
    } 
    if (x[index][type] < y[index][type]) { 
     return -1; 
    } 
    //If sorting by grades return sorting by whatever is diplayed (name, login or id) 
    return (index === 0)? 0 : __sortBySortType(x, y, 0, this.displayType); 
} 

感謝

+0

「最佳」使用替代方法推斷一些評估。沒有評估標準,「最好」僅僅是意見。 – RobG

+0

由於每個分支都被終止,因此這裏的'if'和'else if'之間沒有區別(這只是一種風格選擇)。話雖如此,無論其他結構選擇如何,切換到三元結尾對我來說「看起來很難看」。 – user2864740

+0

我知道我的代碼有效,並且如果我使用其他if,它的工作方式也完全相同。但是我想知道是否有最佳做法規定,因爲我喜歡遵循指導原則。 –

回答

1

給了你必須爲每個if語句返回,不應該有差別。爲了將來的可維護性,最好的做法是做if-elseif-else。我發現一眼就可以輕鬆閱讀,知道它們都是相關的一個選項。

+0

您是否有任何文檔鏈接,請詳細說明您的評論。謝謝 ! –