84.查找数组中某数字第一次出现的索引
使用内置方法 indexOf
function findFirstIndex(arr, target) {
return arr.indexOf(target);
}
// 示例
const array = [2, 5, 3, 7, 3, 8];
console.log(findFirstIndex(array, 3)); // 输出:2(索引从0开始)
console.log(findFirstIndex(array, 9)); // 输出:-1(未找到)
若需查找满足复杂条件的元素(如对象属性匹配),可用 findIndex
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" },
];
const index = users.findIndex((user) => user.id === 2);
console.log(index); // 输出:1