📅  最后修改于: 2023-12-03 15:15:49.433000             🧑  作者: Mango
The indexOf()
method in JavaScript is used to find the index of the first occurrence of a specified value in an array. This method searches through the array from the specified start index and returns the index of the first occurrence of the specified value.
The syntax of the indexOf()
method is as follows:
array.indexOf(searchValue [, fromIndex])
The array
parameter is the array to be searched, and the searchValue
parameter is the value to be searched for. The optional fromIndex
parameter is the index at which to begin the search. If it is not specified, the search will begin at the first element of the array.
searchValue
is found, indexOf()
returns the index of the first occurrence of the value. searchValue
is not found, indexOf()
returns -1.const array1 = [2, 5, 9, 10, 20];
console.log(array1.indexOf(10)); // output: 3
const array2 = ['apple', 'banana', 'orange', 'peach'];
console.log(array2.indexOf('orange', 1)); // output: 2
console.log(array2.indexOf('grape')); // output: -1
In the first example, indexOf()
returns the index of the element '10', which is 3.
In the second example, indexOf()
starts the search from index 1 and returns the index of the element 'orange', which is 2. The third console.log()
statement searches for the element 'grape', which is not found, and therefore returns -1.
For more information about the indexOf()
method, you can refer to the official documentation on MDN.