array.indexof()解析

  • Post category:other

array.indexOf()是JavaScript中的一个数组方法,用于查找数组中指定元素的位置。以下是array.indexOf()的详细攻略,包括语法参数、返回值、示例等。

语法

array.indexOf(searchElement[, fromIndex])

参数

  • searchElement:要查找的素。
  • fromIndex:可选参数,从哪个索引开始查找。如果省略,则从数组的第一个元素开始查找。如果fromIndex为负数,则从数组的末尾开始计算。

返回值

  • 如果找到了指定元素,则该元素在数组中的索引。
  • 如果没有找到指定元素,则返回-1。

示例1:查找数组中的元素

在个示例中,我们将演示如何使用array.indexOf()方法查找数组中的元素。按照以下步骤操作:

  1. 创建一个数组,并在数组中添加一些元素:
const fruits = ['apple', 'banana 'orange', 'pear'];
  1. 使用array.indexOf()方法查找数组中的元素:
const index = fruits.indexOf('banana');
console.log(index); // 输出:1

在这个示例中,我们使用array.indexOf()方法查找数组中的元素”banana”,并返回该元素在数组中的索引1。

示例2:从指定位置开始查找元素

在这个示例中,我们将演示如何使用array.indexOf()方法从指定位置开始查找素。按照以下步骤操作:

  1. 创建一个数组,并在数组中添加一些元素:
const fruits = ['apple', 'banana', 'orange', 'pear'];
  1. 使用array.indexOf()方法从指定位置开始查找元素:
const index = fruits.indexOf('banana',2);
console.log(index); // 输出:-1

在这个示例中,我们使用array.indexOf()方法从索引2开始查找元素”banana”,但是该元素不存在于数组中,因此返回-1。

综上所述,array.indexOf()方法是JavaScript中的一个数组方法,用于查找数组中指定元素的位置。可以通过指定起始位置来查找元素,如果找到了指定元素,则返回该元素在数组中的索引,否则返回-1。