推荐答案
// www.javascriptcn.com code example const array = [1, 2, 3, 4, 5, 4, 3, 2, 1]; // 使用 Array.prototype.findLast() 查找最后一个符合条件的元素 const lastElement = array.findLast((element) => element === 4); console.log(lastElement); // 输出: 4 // 使用 Array.prototype.findLastIndex() 查找最后一个符合条件的元素的索引 const lastIndex = array.findLastIndex((element) => element === 4); console.log(lastIndex); // 输出: 5
本题详细解读
Array.prototype.findLast()
Array.prototype.findLast() 方法用于查找数组中最后一个符合条件的元素。它接受一个回调函数作为参数,该回调函数会对数组中的每个元素进行测试,直到找到最后一个符合条件的元素为止。如果找到符合条件的元素,则返回该元素;否则返回 undefined。
const array = [1, 2, 3, 4, 5, 4, 3, 2, 1]; const lastElement = array.findLast((element) => element === 4); console.log(lastElement); // 输出: 4
在这个例子中,findLast() 方法从数组的末尾开始查找,找到最后一个值为 4 的元素并返回。
Array.prototype.findLastIndex()
Array.prototype.findLastIndex() 方法用于查找数组中最后一个符合条件的元素的索引。它同样接受一个回调函数作为参数,该回调函数会对数组中的每个元素进行测试,直到找到最后一个符合条件的元素为止。如果找到符合条件的元素,则返回该元素的索引;否则返回 -1。
const array = [1, 2, 3, 4, 5, 4, 3, 2, 1]; const lastIndex = array.findLastIndex((element) => element === 4); console.log(lastIndex); // 输出: 5
在这个例子中,findLastIndex() 方法从数组的末尾开始查找,找到最后一个值为 4 的元素并返回其索引 5。
使用场景
findLast():当你需要从数组中查找最后一个符合条件的元素时,可以使用findLast()方法。例如,查找最后一个满足特定条件的用户对象。findLastIndex():当你需要从数组中查找最后一个符合条件的元素的索引时,可以使用findLastIndex()方法。例如,查找最后一个满足特定条件的元素的索引以便进行后续操作。
这两个方法在处理需要从数组末尾开始查找的场景时非常有用,尤其是在处理大型数组或需要反向遍历数组时。