views:

527

answers:

3

I need a javascript function that can take in a string and an array, and return true if that string is in the array..

 function inArray(str, arr){
   ...
 }

caveat: it can't use any javascript frameworks.

+5  A: 

You could just make an array prototype function ala:

Array.prototype.hasValue = function(value) {
  var i;
  for (i=0; i<this.length; i++) { if (this[i] === value) return true; }
  return false;
}

if (['test'].hasValue('test')) alert('Yay!');

Note the use of '===' instead of '==' you could change that if you need less specific matching... Otherwise [3].hasValue('3') will return false.

gnarf
+1. And good idea explaining the difference between '===' and '=='. Only quibble, I'd include the var declaration in the for: for (var i = 0; ...)
Grant Wagner
+1  A: 

Take a look at this related question. Here's the code from the top-voted answer.

function contains(a, obj) {
  var i = a.length;
  while (i--) {
    if (a[i] === obj) {
      return true;
    }
  }
  return false;
}
Dan Walker
+2  A: 

Something like this?

function in_array(needle, haystack)
{
    for(var key in haystack)
    {
        if(needle === haystack[key])
        {
            return true;
        }
    }

    return false;
}
Matthew
I probably should not have used for(key in array). If someone has extended the Array object then it will iterate over the new methods/properties as well (not just the array values).
Matthew