_.sortedIndexOf(array, value)
38
_.sortedIndexOf(array, value)
_.sortedIndexOf类似indexOf,在一个已排序好的数组上用二分法查找元素的索引
参数
array (Array): 需要查找元素索引的数组
value (*): 要查找的元素
返回值
(number):返回元素的索引,找不到返回-1
例子
_.sortedIndexOf([4, 5, 5, 5, 6], 5); // => 1
源代码:
代码调用了baseSortedIndex,前面看过了,省略
import baseSortedIndex from './.internal/baseSortedIndex.js' import eq from './eq.js' /** * This method is like `indexOf` 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 * * sortedIndexOf([4, 5, 5, 5, 6], 5) * // => 1 */ //类似indexOf,在一个已排序好的数组上用二分法查找元素的索引 function sortedIndexOf(array, value) { const length = array == null ? 0 : array.length//数组长度 if (length) {//如果数组有长度 const index = baseSortedIndex(array, value)//调用baseSortedIndex查找位置索引 if (index < length && eq(array[index], value)) { //判断baseSortedIndex查找到的索引上有没有value这个元素,有就返回索引 return index } } return -1//没有就返回-1 } export default sortedIndexOf