提问人:Joe M 提问时间:1/24/2023 最后编辑:Joe M 更新时间:1/24/2023 访问量:50
如何返回 undefined 而不是 -1, findLastIndex()
How to return undefined instead of -1, findLastIndex()
问:
在此质询中,我需要返回回调的最后一个元素的索引位置。我知道 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))
答: 暂无答案
上一个:回调返回语句有问题
评论
let result = array.findLastIndex(callback); if (result === -1) { result = undefined; } return result;