2 回答

TA貢獻1794條經驗 獲得超8個贊
問題是您要為每次嘗試迭代 3 次嘗試。
對于所有嘗試,您需要全局迭代。
換句話說,跟蹤函數之外的嘗試,否則每次調用函數時,您都會將嘗試重置為 3 - 它永遠不會失敗。
這是我對您的代碼的重構,它還修復了一些其他問題并對其進行了優化。
(() => {
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;
}
})();
一些注意事項:
指示性地命名你的變量
將您的 JS 與您的 HTML 分開 - 將其放入專用
.js
文件中。let
這些var
天使用onclick
考慮集中式事件處理,而不是通過屬性內聯 JS 。這也意味著我們不必聲明一個全局函數window
供您onclick
參考。我們將整個內容包裝在 IIFE(立即調用函數表達式)中,以防止污染全局命名空間。
想想每次事件觸發時不需要復制的內容。我們不需要每次都從 DOM 中獲取對相同元素的引用——讓我們在函數之外進行。
array.includes(val)
相當于array.indexOf(val) !== -1
。我還讓用戶無法進行超過 3 次嘗試。

TA貢獻2037條經驗 獲得超6個贊
讓我們看看你的邏輯
<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);
在這一點上,您打開了一個腳本標簽并聲明了一個函數getValue。然后你用 id 從 html 元素中獲取輸入,用 10 個字母"textField"初始化一個數組,然后搜索,返回它的索引。但是,這會導致輸入僅被讀取一次。然后它將執行您的 for 循環進行 3 次迭代,從而產生潛在的有害錯誤。letterslettersinput
這樣想,
您的功能需要在某個地方啟動。通過將其嵌入到 html 中,它將出現onclick()在輸入下方的按鈕中。這意味著每次調用該函數時,都會讀取一次輸入,并且循環在同一個輸入上運行 3 次。我將首先在您的getValue函數之外創建一個變量——我們將調用它——這attempts將允許我們在每次運行函數時更新變量。然后擺脫 for 循環,并使用條件分支,例如
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
}
請評論您不確定的任何內容
添加回答
舉報