我只開始學習如何重構代碼,並且我在抽象一個簡單函數時失敗。我傳遞的參數爲checkAnwser
和它的作品,但count
「丟失」函數不返回值
我不能讓/追加 「計數」 在這裏:
<input data-correctanswer="javascript" id="answer1" name="" type="text">This works fine (no special chars)
<br/>
<button id="btn1">check 1</button>
<br/>
<input data-correctanswer="jávascripté" id="answer2" name="" type="text">
<br/>
<button id="btn2">check 2</button>
<div style="border: 1px solid;" id="result"></div>
的Javascript:
$(document).ready(function() {
var count;
$('#btn1').click(function() {
checkAnswer($('#answer1').data('correctanswer'), $('#answer1').val());
$('#result').append('result: ').append(count); <-- does not read count
}); // end of click
$('#btn2').click(function() {
checkAnswer($('#answer2').data('correctanswer'), $('#answer2').val());
$('#result').append('result: ').append(count); // <-- does not read count
}); // end of click
function checkAnswer(coorAns, UserAnswer) {
var count = 0;
// var coorAns = $('input[type=text]').data('correctanswer');
// var UserAnswer = $('input[type=text]').val();
var mistakesAllowed = 1;
if (UserAnswer === coorAns) {
count = count + 2;
}
for (i = 0; i < coorAns.length; i++) {
if (coorAns.charAt(i) !== UserAnswer.charAt(i)) {
mistakesAllowed--; // reduce one mistake allowed
if (mistakesAllowed < 1) { // and if you have more mistakes than allowed
count = count + 1;
}
if (mistakesAllowed < 0) {
count = count - 2
break;
}
}
}
console.log('final count: ' + count);
return count;
}
});
您正在返回'count',但您並未將其存儲在任何地方,您誤解了變量範圍以及函數返回值的工作原理。 – adeneo
你需要'var count = checkAnswer(args);' – adeneo
我想這就是我首先學習.slideDown()和.addClass()以及之後的實際編程。謝謝:) – Andrejs