📜  Lodash _.lastIndexOf() 方法

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

Lodash _.lastIndexOf() 方法

lodash _.indexOf()方法用于从最后一个元素获取数组中特定元素第一次出现的索引。如果数组中不存在 fromIndex,则给出负数作为输出并且不显示错误。此方法类似于 lodash _.indexOf ,不同之处在于它从右到左迭代数组的元素。

句法:

_.lastIndexOf(array, value, [fromIndex=array.length-1])

注意:如果在数组中未找到该值,则返回 -1。

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

  • 数组:它是要在其中找到值的数组。
  • value:要在数组中查找的值。
  • fromIndex:它是我们必须在其后查找值的索引。

返回值:返回值在数组中的索引。如果未找到该值,则数组返回 -1。

示例 1:

Javascript
// Requiring the lodash library 
const _= require("lodash"); 
    
// Original array 
let array = [1, 2, 2, 3, 4] 
    
// Printing original array  
console.log("Array : ",array) 
    
// Looking for value 3 from Last index   
let index = _.lastIndexOf(array,2) 
    
// Printing the Index of the value  
console.log("Index : ",index)


Javascript
// Requiring the lodash library 
const _= require("lodash"); 
    
// Original array 
let array = [1, 2, 2, 3, 4, 2] 
    
// Printing original array  
console.log("Array : ",array) 
    
// Looking for value 3 from Last index   
let index = _.lastIndexOf(array,2,2) 
    
// Printing the Index of the value  
console.log("Index : ",index)


Javascript
// Requiring the lodash library 
const _= require("lodash"); 
    
// Original array 
let array = [1, 2, 2, 3, 4, 2] 
    
// Printing original array  
console.log("Array : ",array) 
    
// Looking for value 3 from Last index   
let index = _.lastIndexOf(array,4,2) 
    
// Printing the Index of the value  
console.log("Index : ",index)


输出:

示例 2:从特定索引中查找值。

Javascript

// Requiring the lodash library 
const _= require("lodash"); 
    
// Original array 
let array = [1, 2, 2, 3, 4, 2] 
    
// Printing original array  
console.log("Array : ",array) 
    
// Looking for value 3 from Last index   
let index = _.lastIndexOf(array,2,2) 
    
// Printing the Index of the value  
console.log("Index : ",index)

输出:

示例 3:查找不存在的值。

Javascript

// Requiring the lodash library 
const _= require("lodash"); 
    
// Original array 
let array = [1, 2, 2, 3, 4, 2] 
    
// Printing original array  
console.log("Array : ",array) 
    
// Looking for value 3 from Last index   
let index = _.lastIndexOf(array,4,2) 
    
// Printing the Index of the value  
console.log("Index : ",index)

输出: