views:

51

answers:

2

Lets say I have the following array in JavaScript:

var skins = new Array('Light', 'Medium', 'Dark');

How would I go about checking to see what ID in that array (0, 1, or 2) has a matching value to a string I give it. So for example, if I look at a string of 'Medium', I should be returned the ID 1.

+2  A: 

You can use Array.indexOf:

var index = skins.indexOf('Medium'); // 1

This function has been introduced in JavaScript 1.6, but you can include it for compatibility with old browsers.

Here is the algorithm used by Firefox:

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;
  };
}
CMS
A: 
Array.prototype.lastIndex= function(what){
 var L= this.length;
 while(L){
  if(this[--L]=== what) return L;
 }
 return -1;
}

Array.prototype.firstIndex= function(what){
 var i=0, L= this.length;
 while(i<L){
  if(this[i]=== what) return i;
  ++i;
 }
 return -1;
}
kennebec