I guess I should say there is no out of the box contains() method for a javascript array you can create one though by executing the following javascript:
if (!Array.prototype.contains
Array.prototype.contains = function(obj){
var len = this.length;
for (var i = 0; i < len; i++){
if(this[i]===obj){return true;}
}
return false;
};
}
Then you can do things like:
var arrA=['e','b','v'];
alert(arrA.contains('b'));
But this is no more efficient than the brute force method, its just different. There really isn't a way to test if a particular element exists in an Array with out looping through the whole array. (Unless the array is sorted but that is a different story).
Main Topics
Browse All Topics





by: NHBFighterPosted on 2007-05-29 at 15:06:39ID: 19175834
Its not all that efficient but brute force should work.
function contains(arryA,arryB){
for(var i=0;i<arryA.length;i++){
for(var j=0;j<arryB.length;j++){
if(arryA[i]===arryB[j])
return true;
}
}
return false;
}