Javascript array search
What is the best way to find a javascript array to write? All elements will be strings.
Is it easy with lastIndexOf? 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;
}
+3
source to share
4 answers
Is it easy with lastIndexOf?
Yes. However, I would use an even simpler indexOf()
one if you don't need to explicitly look back (which you don't if you are testing for "not contain "). Also note that these methods have been standardized in ES5 and should be customizable in older browsers that don't natively support them.
+5
source to share
You can try building a javascript array method find
. This is the easiest way for your problem. Here is the code:
var list = [], input = "two";
list.push("one");
list.push("two");
list.push("three");
function match(element){
return element == input;
}
if(list.find(match)){
console.log('Match found');
}
+1
source to share