» Programming » JavaScript » Array.indexOf()

This code snippet adds the Array.indexOf() function, making it available to ALL Array objects in JavaScript. This function will return the array index of a given value, or -1 if the item cannot be found within the Array.

1
2
3
4
5
6
7
8
9
10
if ((typeof Array.prototype.indexOf) == "undefined") {
  Array.prototype.indexOf = function(item, start) {
    for (var i = (start || 0); i < this.length; i++) {
      if (this[i] == item) {
        return i;
      }
    }
    return -1;
  }
}