如何返回 undefined 而不是 -1, findLastIndex()

How to return undefined instead of -1, findLastIndex()

提问人:Joe M 提问时间:1/24/2023 最后编辑:Joe M 更新时间:1/24/2023 访问量:50

问:

在此质询中,我需要返回回调的最后一个元素的索引位置。我知道 findLastIndex 返回最后一个索引位置,但是如果回调没有导致 true,我需要返回“undefined”而不是 -1。findLast() 就是这样做的,所以这是我能想到的唯一解决方案。我相信一定有更好的方法,我的方式感觉很傻。我有两个用于测试的数组。

 function findLastTrueElement(array, callback) {

    for(let i = 0; i < array.length; i++) {
  let cb = callback(array[i]) 
 if (cb === true) return array.findLastIndex(callback)
 
}
return array.findLast(callback)
}



 

 const nums = [11, 12, 13, 14, 15, 16, 17, 18, 19];
  //all odd array
 // const nums = [11, 17, 13, 19, 15, 9, 17, 7, 19];
 function isEven(n) {
 return (n % 2 === 0) 
 }
 console.log(findLastTrueElement(nums, isEven))
数组 回调 lastindexof

评论

0赞 John3136 1/24/2023
你似乎错过了相当多的东西。findLastIndex() 适用于数组,因此您不需要在 for 循环中调用它 - 只需在循环中返回 i 或用 findLastIndex() 替换整个循环。如果你没有找到值,为什么不直接返回undefined而不是findLast(你知道这会失败)。
0赞 Joe M 1/24/2023
如果我用 findLastIndex() 替换 for 循环,我如何使用 else 返回 undefined 而不是返回 -1?
0赞 John3136 1/24/2023
let result = array.findLastIndex(callback); if (result === -1) { result = undefined; } return result;
0赞 Joe M 1/24/2023
谢谢约翰!您的回答改变了我对代码可能性的看法。非常感谢。

答: 暂无答案