我已經清理你的代碼,因此很容易增加新的問題,避免了幾乎重複的功能和使用代碼this answer選擇的消息:
var numericalValues = {
Alot: 4,
NotMuch: 2,
NoSometimes: 3,
Hate: 0,
Chocolate: 4,
Carrot: 0,
Both: 2,
None: 0
};
function getScore(name) {
var form = document.forms["form"],
els = form.elements[name];
for(var i=0; i<els.length; i++)
if(els[i].checked)
return numericalValues[els[i].value];
}
var names = ['cake', 'choco'];
function getTotal() {
var scores = [], totalScore = 0;
for(var i=0; i<names.length; ++i)
totalScore += scores[names[i]] = getScore(names[i]);
document.getElementById('result').innerHTML =
getComment(totalScore)
+ '. '+
getAdditionalComment(scores);
}
var comments = [
[0, 'Very Healthy'], /* For 0,1,2 */
[3, 'Neither Healthy nor unhealthy'], /* For 3,4,5,6 */
[7, 'Unhealthy'] /* For 7...Infinity */
],
additionalComments = {
choco: [
[4, 'you eat too much chocolate']/*,
[5, void 0] // Not needed since 4 is maximum */
],
cake: [
[4, 'you have to start a diet']/*,
[5, void 0] // Not needed since 4 is maximum */
]
};
function getValueInRange(arr, n, from, to) {
return (function main(from, to){
if(from>=to) return void 0;
var mid = Math.floor((from+to)/2);
if(arr[mid][0] > n) return main(from, mid);
if(arr[mid][0] < n && mid > from) return main(mid, to);
return arr[mid][1];
})(from===void 0 ? 0 : from, to===void 0 ? arr.length : to);
}
function getComment(score) {
return getValueInRange(comments, score);
}
function getAdditionalComment(scores) {
var arr = [];
for(var i=0, l=names.length; i<l; ++i) {
var txt = getValueInRange(
additionalComments[names[i]],
scores[names[i]]
);
if(txt) arr.push(txt);
}
return arr.join(', ');
}
document.getElementById('calculate').onclick=getTotal;
Demo
在GetAdditionalComment2有一個叫未定義的變量scoreCake。 –
@Dan Iveson,是的,我意外地犯了一個錯誤,好吧,我已經完成了更正,但代碼仍然無法正常工作。 – Acemi