使用FindIndex的函数应该找到A6数组的最新索引,其值从A6_FROM到A6_TO (更多的A6_FROM,但更少的A6_TO)。在OUT-6中显示找到的索引。如果找不到值,则输出FALSE。
let a6 = [13, 15, 22, 23, 26, 35, 72];
let a6_from = 23;
let a6_to = 67;
const f6 = () => {
let res = a6.findIndex((item) => {
return item > a6_from && item < a6_to;
});
document.querySelector('.out-6').innerHTML = `${res}`;
}发布于 2022-03-25 14:39:00
如果找到最新的数组索引,则可以使用
const x = a6[a6.length-1]X将是6的最后一项。
const f6 = () => {
a6.findIndex(item => {
return item === x
})
}如果你想用x找到索引,你可以这样做。
发布于 2022-03-25 15:31:18
这根本不使用findIndex。
它创建一个对象数组来存储a6数组的值和索引。它过滤数组,因此每个值都在a6_from和a6_to之间。然后,它接受最后一个元素的index属性。
let a6 = [13, 15, 22, 23, 26, 35, 72];
let a6_from = 23;
let a6_to = 67;
const meetsCondition = a6.map((value, index) => ({value, index})).filter(e => e.value > a6_from && e.value < a6_to);
const res = meetsCondition[meetsCondition.length - 1].index;
console.log(res);
发布于 2022-03-25 16:43:36
您可以使用map()生成[index, element]对,然后使用filter()只获得元素满足条件的那些对。
用[-1,0]或其他方法准备结果数组,以指示没有找到任何元素。然后使用.pop()[0]获取所需的索引。-1将表明没有找到这样的元素。
const a6 = [13, 15, 22, 23, 26, 35, 72];
const a6_from = 23;
const a6_to = 67;
const a6_out = [[-1,0]].concat(
a6.map((e,i) => [i, e]).filter(([i,e]) => e > a6_from && e < a6_to)
).pop()[0];
//returns -1 if not found
console.log( a6_out );
https://stackoverflow.com/questions/71618550
复制相似问题