Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 668 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Loop through array checking for indexOf's more simple?

#1
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.
Reply

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

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

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

#5
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
}
})
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through