當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Lodash _.findLast()用法及代碼示例

Lodash是一個JavaScript庫,可在underscore.js頂部使用。 Lodash幫助處理數組,集合,字符串,對象,數字等。

_.findLast()方法從右到左遍曆集合中的元素。它與_.find()方法幾乎相同。

用法:

_.findLast( collection, predicate, fromIndex )

參數:此方法接受上述和以下所述的三個參數:

  • collection:方法是對其進行迭代的集合。
  • predicate:每次迭代都會調用該函數。
  • fromIndex:它是從搜索開始的數組的索引。

返回值:此方法返回匹配的元素,否則未定義。



範例1:

// Requiring the lodash library  
const _ = require("lodash");  
      
// Original array  
var users = ([3, 4, 5, 6]); 
  
// Using the _.findLast() method 
let found_elem = _.findLast(users, function(n) { 
  return n % 2 == 1; 
}); 
  
// Printing the output  
console.log(found_elem);

輸出:

5

範例2:

// Requiring the lodash library  
const _ = require("lodash");  
      
// Original array  
var user1 = ([3, 4, 5, 6, 9, 1, 7]); 
var user2 = ([24, 14, 55, 36, 76]); 
  
// Using the _.findLast() method 
let found_elem = _.findLast(user1, function(n) { 
  return n % 2 == 0; 
}); 
let found_elem2 = _.findLast(user2, function(n) { 
  return n % 2 == 1; 
}); 
  
// Printing the output  
console.log(found_elem); 
console.log(found_elem2);

輸出:

6
55

範例3:

// Requiring the lodash library  
const _ = require("lodash");  
      
// Original array  
var user1 = ([3.5, 4.7, 5.8, 6.9, 9.4, 1.3, 7.2]); 
  
// Using the _.findLast() method 
let found_elem = _.findLast(user1, function(n) { 
  return n % 2 == 1; 
}); 
  
// Printing the output  
console.log(found_elem);

輸出:

undefined




相關用法


注:本文由純淨天空篩選整理自shivanisinghss2110大神的英文原創作品 Lodash _.findLast() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。