Is there a function in javascript to do this - test if a given value (a string in my case) exists in an array (of strings)? I know I could just loop over each value, but I'm wondering if js has a shorthand for this.
this would work, I'm using jquery. thanks
bba
2010-10-01 13:01:46
@bba, you might want to add information like that to your question. And to the **tags** for your question. (Edited your question to add the 'jquery' tag.)
David Thomas
2010-10-01 13:03:21
@bba - Be sure to tag your question with jQuery if that's the case, it will get very different answers in many cases. :)
Nick Craver
2010-10-01 13:03:40
Ill be sure to keep that in mind. thanks
bba
2010-10-01 13:04:20
+2
A:
There's .indexOf()
for this, but IE<9 doesn't support it:
if(array.indexOf("mystring") > -1) {
//found
}
From the same MDC documentation page, here's what to include (before using) to make IE work as well:
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
.indexOf()
returns the index in the array the string was found at, or -1
if it wasn't found.
Nick Craver
2010-10-01 13:01:13
A:
For functions that are in php and should be in javascript or I haven't found yet I go to: http://phpjs.org
The function you want use if you're just using javascript is in_array here: http://phpjs.org/functions/in_array:432
Otherwise, use the jQuery solution on this page.
BenWells
2010-10-01 13:20:10