findIndex()
是 JavaScript 数组的一个内置方法,用于查找数组中满足指定条件的元素的索引。
如果数组中有符合条件的元素,则返回第一个满足条件的元素的索引。
如果数组中没有符合条件的元素,则 findIndex()
方法会返回 -1
。
下面是 findIndex()
方法的基本用法1:
<script>
list = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' }
];
// 使用 findIndex 方法查找id=1 的元素的索引
const index = list.findIndex(e => e.id === 1);
console.log(index); //输出:0,因为第一个等于 0 的元素在索引 0 处
</script>
下面是 findIndex()
方法的基本用法2:
const array = [5, 12, 8, 130, 44];
// 使用 findIndex 方法查找大于 10 的元素的索引
const index = array.findIndex(e=> e> 10);
console.log(index); // 输出:1,因为第一个大于 10 的元素在索引 1 处(值为 12)