0Day Forums
Loop through array checking for indexOf's more simple? - Printable Version

+- 0Day Forums (https://0day.red)
+-- Forum: Coding (https://0day.red/Forum-Coding)
+--- Forum: JScript (https://0day.red/Forum-JScript)
+--- Thread: Loop through array checking for indexOf's more simple? (/Thread-Loop-through-array-checking-for-indexOf-39-s-more-simple)



Loop through array checking for indexOf's more simple? - boer474 - 07-24-2023

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.


RE: Loop through array checking for indexOf's more simple? - Mrmastigophorousi - 07-24-2023

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


RE: Loop through array checking for indexOf's more simple? - hakanvojuc - 07-24-2023

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


RE: Loop through array checking for indexOf's more simple? - bevypionjii - 07-24-2023

Try using a [regular expression](

[To see links please register here]

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


RE: Loop through array checking for indexOf's more simple? - talkfest11717 - 07-24-2023

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