2014-10-29 52 views
0

我想通過刪除所有那些if statements來簡化此代碼,如果可能的話,單個函數和/或可用於刪除這些元素的所有內容(如果有的話)。當檢查多個整數範圍時,替換多個if語句

我需要檢查多個整數範圍,並根據用戶評分我需要設置兩個變量。

這是我的代碼:

if (userScore <= 40) 
{ 
    object.setMinValue(0); 
    object.setMaxValue(40); 
} 

if (userScore > 40 && userScore <= 65) 
{ 
    object.setMinValue(41); 
    object.setMaxValue(65); 
} 

if (userScore > 65 && userScore <= 85) 
{ 
    object.setMinValue(66); 
    object.setMaxValue(85); 
} 

if (userScore > 85 && userScore <= 95) 
{ 
    object.setMinValue(86); 
    object.setMaxValue(95); 
} 

if (userScore > 95 && userScore <= 100) 
{ 
    object.setMinValue(96); 
    object.setMaxValue(100); 
} 

我認爲一個switch聲明可以使用,因爲有很多if statements來檢查同一個變量,但有一個更簡單,更有效的[性能expecially]解?

感謝

+0

http://stackoverflow.com/questions/2696436/switch-case-in-jquery – sasi 2014-10-29 10:16:49

+0

switch語句不能在這裏使用,因爲你有範圍,而不是固定值。 – 2014-10-29 10:23:24

回答

2

首先,這不是很好的使用object在javascript中的變量名。我使用'o'代替。 我可以從你的代碼搞清楚,在代碼塊的值可以從條件語句中得到:

var scoreLimits = [0,40,65,85,95,100]; 

for(var i = 1; i < scoreLimits.length; i++) 
{ 
    var limit = scoreLimits[i]; 
    if (userScore <= limit) 
    { 
     o.setMinValue(scoreLimits[i-1]); 
     o.setMaxValue(limit); 
     break; 
    } 
} 

這裏是一個工作示例: http://jsfiddle.net/xsasjs6t/

如果你希望它運行的真快,你可以預先計算地圖可能userScore值的整個範圍,並在以後使用它:

var mapper = {}; 
for(var i = 0; i < scoreLimits.length - 1; i++) 
{ 
    var limits = { minValue : scoreLimits[i], maxValue : scoreLimits[i+1] }; 
    for (var j = scoreLimits[i] + 1; j <= scoreLimits[i + 1]; j++) 
    { 
     mapper[j] = limits; 
    } 
} 

工作例如: http://jsfiddle.net/8cqwp4fz/

+0

你好喬治,在我原來的代碼中,我沒有使用「對象」,而是使用其他變量名,但發佈了我用它替換的問題。感謝您的回答 :-) – Aluminum 2014-10-29 10:18:35