Question

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.

Was it helpful?

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]);
    }
}

OTHER TIPS

Try using a regular expression to match the message. The \b is a word boundary marker, and the words between the | characters are what is being searched for. If any of the words appear in the message, then message.match will return the array of matches, otherwise null.

var pattern = /\b(Hello|Hi|Hiya)\b/i;
var message = "Hello World";
if (message.match(pattern))
{
    console.log("do stuff");
}

You can write even simpler using a for in loop:

for(var v in hiTriggers){
    if(message.indexOf(hiTriggers[v]) >= 0) {
        //do stuff here
        console.log("found " + hiTriggers[v]);
    }
}

Problem is becoz - you have not initialized your var i, make it var i = 0;

You can try forEach loop.

hiTriggers.forEach(function(e) {

  if(message.indexOf(e) >= 0) {
   //do sthg here
  }
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top