Array.indexOf()方法用于返回数组中指定元素的第一个索引位置,如果数组中不存在该元素,则返回-1。
以下是一个使用Array.indexOf()方法的代码示例:
const array = [1, 2, 3, 4, 5];
console.log(array.indexOf(3)); // 输出2,因为3在数组中的索引位置是2
console.log(array.indexOf(6)); // 输出-1,因为6不在数组中
在上面的示例中,我们创建了一个数组array
,然后使用indexOf()
方法分别查找元素3和6在数组中的索引位置。输出结果显示,元素3的索引位置是2,而元素6不在数组中,所以返回-1。
需要注意的是,indexOf()
方法只返回第一个匹配的索引位置。如果数组中存在多个相同的元素,它将返回第一个匹配的索引位置。
此外,indexOf()
方法还可以接收第二个参数,表示从指定的索引位置开始查找。例如:
const array = [1, 2, 3, 4, 5];
console.log(array.indexOf(3, 2)); // 输出2,从索引位置2开始查找元素3的索引位置
console.log(array.indexOf(3, 3)); // 输出-1,从索引位置3开始查找元素3,但是数组中没有后续的元素3