js array findindexof 用法
时间: 2023-10-09 10:13:51 浏览: 37
JavaScript 中的数组有一个 `indexOf()` 方法,它可以用来查找数组中指定元素的位置。这个方法接受一个参数,即要查找的元素,返回该元素在数组中第一次出现的位置。如果该元素不存在,则返回 -1。
例如:
```javascript
const arr = [1, 2, 3, 4, 5];
const index = arr.indexOf(3);
console.log(index); // 输出 2
```
在 ECMAScript 2015 (ES6) 中,还新增了一个名为 `findIndex()` 的方法,它可以根据指定的条件查找数组中第一个符合条件的元素,并返回该元素在数组中的位置。这个方法接受一个回调函数作为参数,该回调函数会被传入数组中的每一个元素,如果回调函数返回 true,则 `findIndex()` 方法返回该元素在数组中的位置;如果所有元素都不符合条件,则返回 -1。
例如:
```javascript
const arr = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' },
{ id: 4, name: 'David' }
];
const index = arr.findIndex((item) => item.id === 3);
console.log(index); // 输出 2
```
这里的 `findIndex()` 方法会遍历数组中的每一个元素,传入的回调函数根据元素的 `id` 属性判断是否符合条件,找到第一个符合条件的元素后返回该元素在数组中的位置。