Search code examples
javascriptfor-loopjscript

Loop through array checking for indexOf's more simple?


Okay, like the title says. I have a array looking like this:

var hiTriggers = new Array();
hiTriggers = ["hi", "hai", "hello"];

And I'd like to check through it if it finds either of those. I can already achieve this by doing the following:

if(message.indexOf("hi") >= 0) {
   // do whatever here!
}

But I'm looking for an more efficient way rather than doing 100 if() checks. Such as loop through an array with the "hiTriggers".

I tried the following:

for(var i; i < hiTriggers.length; i++) {
    console.log(hiTriggers[i]); // simply to know if it checked them through)
    if(message.indexOf(hiTriggers[i]) >= 0) {
    //do stuff here
}
}

Which sadly did not work as I wanted as it does not check at all. Thanks in advance and I hope I made sense with my post!

Edit; please note that I have 'messaged' already 'declared' at another place.


Solution

  • It doesn't run because you didn't give the i variable an initial value. It is undefined.

    Change to use var i=0;:

    for(var i=0; i < hiTriggers.length; i++) {
        //console.log(hiTriggers[i]); // simply to know if it checked them through)
        if(message.indexOf(hiTriggers[i]) >= 0) {
            //do stuff here
            console.log("found " + hiTriggers[i]);
        }
    }