arr.findIndex() 返回 -1 表示在数组 arr 中没有找到满足给定条件的元素。以下是几种可能的解决方法的代码示例:
const arr = [1, 2, 3, 4, 5];
const target = 6;
const index = arr.findIndex(element => element === target);
if (index === -1) {
console.log("元素不存在");
} else {
console.log(`元素存在于索引 ${index}`);
}
const arr = [1, 2, 3, 4, 5];
const target = 6;
const index = arr.findIndex(element => element > target);
if (index === -1) {
console.log("没有找到满足条件的元素");
} else {
console.log(`找到满足条件的元素于索引 ${index}`);
}
const arr = [1, 2, 3, 4, 5];
const target = 6;
const exists = arr.includes(target);
if (!exists) {
console.log("元素不存在");
} else {
console.log("元素存在");
}
这些示例提供了几种不同的方法来解决 arr.findIndex() 返回 -1 的情况。具体使用哪种方法取决于你的需求和代码背景。