Whats the best way to search a javascript array for an entry?? All the items will be strings.
Is it simply by using lastIndexOf? like so:
var list= [];
list.push("one");
list.push("two");
list.push("three");
if(list.lastIndexOf(someString) != -1)
{
alert("This is already present in list");
return;
}
Is it simply by using lastIndexOf?
Yes. However, I'd use even simpler indexOf() if you don't need to explicitly search backwards (which you don't if you test for "does not contain"). Also notice that these methods were standardized in ES5 and need to be shimmed in old browsers that do not support them natively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With