Reputation: 25552
I have a script that I am working on that I am a little lost on.
I grab a user input (using jQuery) and then loop through an array and see if a phrase from the array exists in the user input. If it is found I am popping up an alert box telling them its found. But for some reason its not working.
Code:
submit = false;
for(i in keyphrases_array) {
if(english_text.indexOf(keyphrases_array[i]) != -1) {
if(trans_text.indexOf(keyphrases_array[i]) != -1) {
submit = false;
}
} else {
submit = true;
}
}
keyphrases_array
is a global array that is set in another function.
Example:
If in my array I have the phrase "Hello World" and my script finds Hello World in the english_text
variable it then checks the user submitted text (trans_text
). If the phrase is not found in trans_text
then the script should return false.
Upvotes: 1
Views: 1393
Reputation: 728
The previous code would return true if the text was only in the english version, you need to only pass true if it's in both. - Did I understand correctly?
submit = false;
for(i in keyphrases_array) {
if(english_text.indexOf(keyphrases_array[i]) != -1 && trans_text.indexOf(keyphrases_array[i]) != -1) {
submit = true;
}
} else {
submit = false;
}
}
EDIT: Switched true / false around to match the question
Upvotes: 1
Reputation: 322622
First, you shouldn't use for/in
to iterate over an array. Use a plain for
loop.
The problem is likely that the value of submit
is being overwritten by the next iteration in the loop. If that's the end of the function, you should return immediately.
submit = false;
for(var i = 0; i < keyphrases_array.length; i++) {
if(english_text.indexOf(keyphrases_array[i]) != -1) {
if(trans_text.indexOf(keyphrases_array[i]) != -1) {
// return immediately
return false;
}
} else {
submit = true;
}
}
return submit;
or if there needs to be more processing, you can just break the loop:
submit = false;
for(var i = 0; i < keyphrases_array.length; i++) {
if(english_text.indexOf(keyphrases_array[i]) != -1) {
if(trans_text.indexOf(keyphrases_array[i]) != -1) {
submit = false;
break;
}
} else {
submit = true;
}
}
EDIT: Based on your comment, it seems that you want to return false
if the text is not found in trans_text
. This would meant that the test should use ==
instead of !=
.
if(trans_text.indexOf(keyphrases_array[i]) == -1) {
// return immediately
return false;
}
Upvotes: 3