Objectives :
- to have the user type the shown words in the input fields.
- to check if the typed word are exact copy of the ones that were asked.
- if yes, then go on to the next one
- if no, then ask to type again the wrongly typed word
All the words are included in an array.
What works so far :
objectives 1 to 3 work great !
What doesn’t work :
Objective 4 partially works. The problem is that it restarts the whole loop instead of keeping track of the progress so far and only restart from the wrongly answered question.
The code :
wordList = ["Cachalot", "Pétunia", "Serviette"]
score = 0
for (let i=0; i<wordList.length; i++){
let typedWord = prompt("Veuillez recopier le mot suivant : " + wordList[i])
if(typedWord===wordList[i]){
score+=1
console.log(score)
} else{
console.log ("merci de recommencer")
typeSmart()
}
}
}typeSmart()
I know calling the function is due to start the whole process again. But I’m a bit clueless as how to do otherwise. should I use a while instead or in complement of the current for loop ?
2
Answers
Add
--i;
in yourelse
statement. This will keep the value ofi
for thefor
loop the same, untill the user enters the correct answer. So it will keep prompting the same prompt, until the user enters rhe correct answer, which serves your purpose.Yes, use a
while
loop instead. As you don’t know how many times you’re going to be asking for the word (ie: looping), awhile
loop is more appropriate.for
loops are typically better for when you know the number of times in advance you need to loop, which isn’t the case here.When the user gets the word correct, you can advance the index of the current word you’re looking at (in the below snippet I’ve called that
currentWordIdx
). Also, make sure you declare your variables withlet
orconst
(var
is also an option but not preferred), otherwise they become global variables and may impact other parts of your code outside of your function unintentionally: