How do you use the indexOf method in JavaScript?
The indexOf() method in JavaScript is used to find the index position of a specified element in an array. It returns the index value of the element if found, or -1 if not found.
Grammar: Syntax
array.indexOf(item, start)
Parameter:
- element to be searched for
- start: optional parameter that specifies the index position to start searching from, with a default value of 0.
示例:Example
var fruits = ["apple", "banana", "orange", "grape"];
var index = fruits.indexOf("orange");
console.log(index); // 输出:2
var index2 = fruits.indexOf("watermelon");
console.log(index2); // 输出:-1
In the example above, return the index value of “orange” if it exists in the array fruits; return -1 if “watermelon” is not in the array.