PDA

View Full Version : in array?



nikko50
Oct 25th, 2011, 04:05 AM
So if I create an array like below how can I test whether the value in "field1" is in the array?


var field1 = document.theForm.car.value;
var myCars = new Array();
var myCars=["Saab","Volvo","BMW"];

Old Pedant
Oct 25th, 2011, 04:14 AM
If you want to be compatible with all browsers, you just code it as a loop:


var foundAt = -1;
for ( var m = 0; m < myCars.length; ++m )
{
if ( myCars[m] == field1 ) { foundAt = m; break; }
}
// if you get here and foundAt is still < 0 then it wasn't found

rnd me
Oct 25th, 2011, 04:46 PM
[].indexOf is a standard methods, but it didn't make it into IE8...

if your array contains strings only, use can use String's indexOf or search:


var field1 ="BMW";

var myCars=["Saab","Volvo","BMW"];

inArray=String.prototype.search.call( myCars, RegExp(",?"+field1+",?"))!= -1;

this works in all browsers.