Categories
JavaScript Tutorials

Location Methods

ECMAScript 5 adds two item location methods to array instances: indexOf() and lastIndexOf().

Each of these methods accepts two arguments: the item to look for and an optional index from which to start looking. The indexOf() method starts searching from the front of the array (item 0) and continues to the back, whereas lastIndexOf() starts from the last item in the array and continues to the front.

The methods each return the position of the item in the array or –1 if the item isn’t in the array. An identity comparison is used when comparing the first argument to each item in the array, meaning that the items must be strictly equal as if compared using ===. Here are some examples of this usage:

var numbers = [1,2,3,4,5,4,3,2,1];
alert(numbers.indexOf(4)); //3
alert(numbers.lastIndexOf(4)); //5
alert(numbers.indexOf(4, 4)); //5
alert(numbers.lastIndexOf(4, 4)); //3
var person = { name: "Nicholas" };
var people = [{ name: "Nicholas" }];
var morePeople = [person];
alert(people.indexOf(person)); //-1
alert(morePeople.indexOf(person)); //0