我試圖簡化這個功能,因爲可以有多個type
數據對象,並且每種類型都有一個男性版本和一個女性版本。 對象中元素的編號和名稱始終相同。通過重複if/else部分來簡化函數
正如你看到的,大部分代碼是重複......
function calculate(type, j, value, s) {
for (var i = j; i > 4; i--) {
if (type == 'weight') {
if (s == 'f') {
if (weightFemale.hasOwnProperty(i)) {
var m = weightFemale[i][0],
l = weightFemale[i][1],
s = weightFemale[i][2];
return getcalc(m,l,s);
}
}
else {
if (weightMale.hasOwnProperty(i)) {
var m = weightMale[i][0],
l = weightMale[i][1],
s = weightMale[i][2];
return getcalc(m,l,s);
}
}
}
else if (type == 'length') {
if (s == 'f') {
if (lengthFemale.hasOwnProperty(i)) {
var m = lengthFemale[i][0],
l = lengthFemale[i][1],
s = lengthFemale[i][2],
return getcalc(m,l,s);
}
}
else {
if (lengthMale.hasOwnProperty(i)) {
var m = lengthMale[i][0],
l = lengthMale[i][1],
s = lengthMale[i][2],
return getcalc(m,l,s);
}
}
}
}
return false;
}
我怎麼能簡化的if/else零件的類型和性?
爲你的代碼似乎是你可能會考慮在codereview.stackexchange.com上詢問這個問題。至於這個問題,爲重複部分製作一個函數可能會有所幫助。 –
我投票結束這個問題作爲題外話,因爲它應該在像codereview.stackexchange – rlemon
這樣的網站首先這個代碼工作正常嗎?因爲's ='f''需要's''f''。 –