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
returnkeyword stops the execution of yourforloop once a condition is met. In your case, bothifandelsehavereturnkeyword in them, so yourforloop will never execute more then once.In other words, your
ifstatement 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
elsestatement, because variableiwould be 0 (AKA 'blue' in your array). By going inelseit 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 :