📜  Lodash _.sortedIndexOf() 方法

📅  最后修改于: 2022-05-13 01:56:51.048000             🧑  作者: Mango

Lodash _.sortedIndexOf() 方法

_.sortedIndexOf() 方法用于获取排序数组中特定元素的第一次出现的索引。它使用二进制搜索对数组进行排序。

句法:

_.sortedIndexOf(array, value)

参数:此方法接受上面提到的两个参数,如下所述:

  • array:此参数保存已排序的数组。
  • value:此参数保存要评估的值。

返回值:此方法返回值应插入数组的索引,其他返回-1。

示例 1:这里使用 const _ = require('lodash') 将 lodash 库导入文件。

Javascript
// Requiring the lodash library 
const _ = require("lodash"); 
    
// Original array 
let x = [1, 2, 3, 4, 4, 4, 5, 6, 6]  
    
// Use of _.sortedIndexOf() 
// method 
let index = _.sortedIndexOf(x, 4);
    
// Printing the output 
console.log(index);


Javascript
// Requiring the lodash library 
const _ = require("lodash"); 
    
// Original array 
let x = ['a', 'b', 'c', 'd', 'e', 'e', 'e', 'f']  
    
// Use of _.sortedIndexOf() 
// method 
let index = _.sortedIndexOf(x, 'e');
    
// Printing the output 
console.log(index);


Javascript
// Requiring the lodash library 
const _ = require("lodash"); 
    
// Original array 
let x = ['ajax', 'django', 'mongoDb',  
       'react', 'reactnative', 'yarn']  
    
// Use of _.sortedIndexOf() 
// method 
let index = _.sortedIndexOf(x, 'luby');
    
// Printing the output 
console.log(index);


输出:

3

示例 2:

Javascript

// Requiring the lodash library 
const _ = require("lodash"); 
    
// Original array 
let x = ['a', 'b', 'c', 'd', 'e', 'e', 'e', 'f']  
    
// Use of _.sortedIndexOf() 
// method 
let index = _.sortedIndexOf(x, 'e');
    
// Printing the output 
console.log(index);

输出:

4

示例 3:

Javascript

// Requiring the lodash library 
const _ = require("lodash"); 
    
// Original array 
let x = ['ajax', 'django', 'mongoDb',  
       'react', 'reactnative', 'yarn']  
    
// Use of _.sortedIndexOf() 
// method 
let index = _.sortedIndexOf(x, 'luby');
    
// Printing the output 
console.log(index);

输出:

-1

注意:这在普通 JavaScript 中不起作用,因为它需要安装库 lodash。