JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

7.9.6 indexOf() and lastIndexOf()

7.9.6 indexOf() and lastIndexOf()

indexOf() and lastIndexOf() search an array for an element with a specified value, and return the index of the first such element found, or –1 if none is found. indexOf() searches the array from beginning to end, and lastIndexOf() searches from end to beginning.

a = [0,1,2,1,0]; a.indexOf(1) // => 1: a[1] is 1 a.lastIndexOf(1) // => 3: a[3] is 1 a.indexOf(3) // => -1: no element has value 3

Unlike the other methods described in this section, indexOf() and lastIndexOf() do not take a function argument. The first argument is the value to search for. The second argument is optional: it specifies the array index at which to begin the search. If this argument is omitted, indexOf() starts at the beginning and lastIndexOf() starts at the end. Negative values are allowed for the second argument and are treated as an offset from the end of the array, as they are for the splice()method: a value of –1, for example, specifies the last element of the array.

The following function searches an array for a specified value and returns an array of all matching indexes. This demonstrates how the second argument to indexOf() can be used to find matches beyond the first.

// Find all occurrences of a value x in an array a and return an array

// of matching indexes

function findall(a, x) {

var results = [], // The array of indexes we'll return

len = a.length, // The length of the array to be searched

pos = 0; // The position to search from

while(pos < len) { // While more elements to search...

pos = a.indexOf(x, pos); // Search

if (pos === -1) break; // If nothing found, we're done.

results.push(pos); // Otherwise, store index in array

pos = pos + 1; // And start next search at next element


return results; // Return array of indexes


Note that strings have indexOf()and lastIndexOf() methods that work like these array methods.

友情链接It题库(| 版权归yishouce.com所有| 友链等可联系|粤ICP备16001685号-1