0

I'm working on a chrome extension and I'm using a lot of if statements to check the webpage for a list of words. And I have to continuously type each word over and over again but I'm wondering if there was a way to check the words one time through a list.

Currently I'm kinda working like this:

if (text == "apple")
if (text == "orange")
if (text == "Banana")
if (text == "Cherry")
if (text == "Lime")

and so on.. But is there a way to check a list of these words so I don't have so many if statements?

I was thinking of something like this:

List = "apple", "orange", "Banana", "Cherry", "Lime"

   if (text == "list")

Is something like this possible in a Google Chrome Extension?

Jake
  • 63
  • 1
  • 6

3 Answers3

5

Make your list of words into an array, and then you could do a simple using indexOf. For example:

var list = ["apple", "orange", "Banana", "Cherry", "Lime"];

and then you could check the list with: (Thanks to @Edwin for making it even shorter)

if(list.indexOf(text));
Alex J
  • 1,029
  • 6
  • 8
0

You can use for to loop through it:

var list = ["apple", "orange", "Banana", "Cherry", "Lime"];

for(var i = 0; i < list.length; i++) {
    if(list[i] == text) {
        // text WAS FOUND !
        break;
    }
}

Hope this help ! Cheers,

cram2208
  • 416
  • 6
  • 14
0
var list = ["apple", "orange", "Banana", "Cherry", "Lime"];

var doesExist = list.some(function(word){
 return text == word;
}); //boolean

if(doesExist) {

}

Depends what you want to do, because in the function you can do complicated checks or whatever. But if it's something simple I'd go with the other answer with indexOf

Edwin Reynoso
  • 1,511
  • 9
  • 18