2 回答

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超7個(gè)贊
問題是您要為每次嘗試迭代 3 次嘗試。
對于所有嘗試,您需要全局迭代。
換句話說,跟蹤函數(shù)之外的嘗試,否則每次調(diào)用函數(shù)時(shí),您都會將嘗試重置為 3 - 它永遠(yuǎn)不會失敗。
這是我對您的代碼的重構(gòu),它還修復(fù)了一些其他問題并對其進(jìn)行了優(yōu)化。
(() => {
let attempts = 3,
input_el = document.getElementById('textField'),
result_el = document.getElementById('valueReturned');
window.getValue = () => {
let input = input_el.value,
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
correct = letters.includes(input),
msg;
if (!attempts)
msg = 'No attempts left!';
else if (!input)
msg = "No input!";
else if(!correct) {
attempts--;
switch (attempts) {
case 2:
msg = 'Two tries left!'
break;
case 1:
msg = 'One more try!';
break;
case 0:
msg = 'That was your last try! Get lost!';
break;
}
} else
msg = 'You guessed right!';
result_el.innerHTML = msg;
}
})();
一些注意事項(xiàng):
指示性地命名你的變量
將您的 JS 與您的 HTML 分開 - 將其放入專用
.js
文件中。let
這些var
天使用onclick
考慮集中式事件處理,而不是通過屬性內(nèi)聯(lián) JS 。這也意味著我們不必聲明一個(gè)全局函數(shù)window
供您onclick
參考。我們將整個(gè)內(nèi)容包裝在 IIFE(立即調(diào)用函數(shù)表達(dá)式)中,以防止污染全局命名空間。
想想每次事件觸發(fā)時(shí)不需要復(fù)制的內(nèi)容。我們不需要每次都從 DOM 中獲取對相同元素的引用——讓我們在函數(shù)之外進(jìn)行。
array.includes(val)
相當(dāng)于array.indexOf(val) !== -1
。我還讓用戶無法進(jìn)行超過 3 次嘗試。

TA貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超6個(gè)贊
讓我們看看你的邏輯
<script>
function getValue(){
var input = document.getElementById("textField").value;
var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] ;
var a = letters.indexOf(input);
在這一點(diǎn)上,您打開了一個(gè)腳本標(biāo)簽并聲明了一個(gè)函數(shù)getValue。然后你用 id 從 html 元素中獲取輸入,用 10 個(gè)字母"textField"初始化一個(gè)數(shù)組,然后搜索,返回它的索引。但是,這會導(dǎo)致輸入僅被讀取一次。然后它將執(zhí)行您的 for 循環(huán)進(jìn)行 3 次迭代,從而產(chǎn)生潛在的有害錯(cuò)誤。letterslettersinput
這樣想,
您的功能需要在某個(gè)地方啟動。通過將其嵌入到 html 中,它將出現(xiàn)onclick()在輸入下方的按鈕中。這意味著每次調(diào)用該函數(shù)時(shí),都會讀取一次輸入,并且循環(huán)在同一個(gè)輸入上運(yùn)行 3 次。我將首先在您的getValue函數(shù)之外創(chuàng)建一個(gè)變量——我們將調(diào)用它——這attempts將允許我們在每次運(yùn)行函數(shù)時(shí)更新變量。然后擺脫 for 循環(huán),并使用條件分支,例如
var attempts = 0;
function getValue(){
var input = document.getElementById("textField").value;
var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] ;
var a = letters.indexOf(input);
if (attempts < 3) {
// check if input is right
if (input != "" && a != -1) {
alert("success");
}
attempts += 1;
}
// no else statement needed to terminate the program
// simply don't handle occurrences of attempts greater than 3
}
請?jiān)u論您不確定的任何內(nèi)容
添加回答
舉報(bào)