_.sortedLastIndexOf(array, value)
41
_.sortedLastIndexOf(array, value)
_sortedLastIndexOf方法类似lastIndexOf,在一个已排序好的数组上用二分法查找元素的索引
参数
array (Array): 查找元素索引的数组
value (*): 要查找的值
返回值
(number): 返回查找到的元素的索引,找不到返回-1
例子
_.sortedLastIndexOf([4, 5, 5, 5, 6], 5); // => 3
源代码:
调用了baseSortedIndex,之前看过了,省略
import baseSortedIndex from './.internal/baseSortedIndex.js' import eq from './eq.js' /** * This method is like `lastIndexOf` except that it performs a binary * search on a sorted `array`. * * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * sortedLastIndexOf([4, 5, 5, 5, 6], 5) * // => 3 */ //类似lastIndexOf,在一个已排序好的数组上用二分法查找元素的索引 function sortedLastIndexOf(array, value) { const length = array == null ? 0 : array.length//数组的长度 if (length) {//如果数组有长度 const index = baseSortedIndex(array, value, true) - 1//调用baseSortedIndex找到元素应该插入的位置然后减1 if (eq(array[index], value)) {//如果找到位置的元素和value相等,就返回索引 return index } } return -1//否则返回-1 } export default sortedLastIndexOf

浙公网安备 33010602011771号