Use the new (ECMAScript 5) Array object methods indexOf and lastIndexOf:
Though support for both indexOf and lastIndexOf has existed in browsers for some time, it’s only been formalized with the release of ECMAScript 5. Both methods take a search value, which is then compared to every element in the array. If the value is found, both return an index representing the array element. If the value is not found, –1 is returned. The indexOf method returns the first one found, the lastIndexOf returns the last one found:
Both methods can take a starting index, setting where the search is going to start:
Currently, all of the book’s target browsers support indexOf and lastIndexOf, except for IE8.
As mentioned, not all browsers support indexof and lastIndexOf. A cross-browser method to implement like functionality in these browsers is given in the Mozilla documentation, at https://developer.mo...s/Array/indexOf. Since IE8 doesn’t support indexOf, here’s the Mozilla workaround for the function:
var animals = new Array("dog","cat","seal","elephant","walrus","lion"); alert(animals.indexOf("elephant")); // prints 3
Though support for both indexOf and lastIndexOf has existed in browsers for some time, it’s only been formalized with the release of ECMAScript 5. Both methods take a search value, which is then compared to every element in the array. If the value is found, both return an index representing the array element. If the value is not found, –1 is returned. The indexOf method returns the first one found, the lastIndexOf returns the last one found:
var animals = new Array("dog","cat","seal","walrus","lion", "cat"); alert(animals.indexOf("cat")); // prints 1 alert(animals.lastIndexOf("cat")); // prints 5
Both methods can take a starting index, setting where the search is going to start:
var animals = new Array("dog","cat","seal","walrus","lion", "cat"); alert(animals.indexOf("cat",2)); // prints 5 alert(animals.lastIndexOf("cat",4)); // prints 1
Currently, all of the book’s target browsers support indexOf and lastIndexOf, except for IE8.
As mentioned, not all browsers support indexof and lastIndexOf. A cross-browser method to implement like functionality in these browsers is given in the Mozilla documentation, at https://developer.mo...s/Array/indexOf. Since IE8 doesn’t support indexOf, here’s the Mozilla workaround for the function:
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;
};
}



