Tuesday, August 21, 2012

Javascript fallback for jQuery $.inArray

Sometimes, for whatever reason, someone doesn't want you to use jQuery.  It helps to know this from the beginning, so ask first.

Here is the javascript fallback for one of my favorite jQuery methods, $.inArray();

function contains (needle,haystack) {
   for (var i=0; i < haystack.length; i++) {
      if (needle == haystack[i]) {
         return true;
      }
   }
   return false;
}

Sending your two values, needle and haystack, to this function will return true on success ( the value is in the array ) or false if it is not.

Example

var favBeers = ["Laguinitas IPA", "Bear Republic Racer 5 IPA", "Deschutes Mirror Pond Pale Ale"];
var aBeer = "Corona";

if  (contains(aBeer, favBeers)) {
   //   nothing happens here because Corona sucks.
}

No comments:

Post a Comment