I am working on coding in my Computer Science class and my function isn’t working correctly. I rewrote my code to make an example:
function getWords(userWord) {
var returnList = [];
var wordList = [blue, red, purple];
for (var i = 0; i < wordList.length; i++) {
if (userWorld == wordList[i]) {
appendItem(returnList, wordList[i]);
return returnList[];
} else {
return “Not Found.”;
}
}
}
I try this and it will only return “Not Found.” even if the word matches.
If you are using JavaScript, I solved your issue. :)
You had some misspelling, and some errors in your code.
See, the problem is that
return
keyword stops the execution of yourfor
loop once a condition is met. In your case, bothif
andelse
havereturn
keyword in them, so yourfor
loop will never execute more then once.In other words, your
if
statement will work only if you put word 'blue'.If you were to put word 'red', which is the second element in your array, you would obviously go into
else
statement, because variablei
would be 0 (AKA 'blue' in your array). By going inelse
it will return 'Not found.' and it would stop the for loop completely.Hope you understand now :)
Anyways, here is your solution friend, let me know if it works, or if you have any questions :