📜  Lodash _.invoke() 方法

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

Lodash _.invoke() 方法

Lodash 是一个基于 underscore.js 的 JavaScript 库。 Lodash 有助于处理数组、集合、字符串、语言、函数、对象、数字等。

_.invoke() 方法在对象路径处调用方法。

句法:

_.invoke(object, path, args)

参数:此方法接受三个参数,如上所述,如下所述:

  • object:它保存要查询的对象。
  • path:它保存调用元素的方法的路径。
  • args:调用方法的参数。

返回值:该方法返回被调用方法的结果。

示例一:这里使用 const _ = require('lodash') 来导入文件中的 lodash 库。

// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var object = { 'p': [{ 'q': { 'r': [ 3, 5, 7, 9 ] } }] };
  
// Using the _.invoke() method
let invt_elem = _.invoke(object, 'p[0].q.r.slice', 3, 7);
  
// Printing the output 
console.log(invt_elem);

输出:

[ 9 ]

示例 2:

// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var object = { 'p': [{ 'q': { 'r': { 's': [ 2, 4, 6, 8, 10 ] 
  
} } }] };
  
// Using the _.invoke() method
let invt_elem = _.invoke(object, 'p[0].q.r.s.slice', 2, 5);
  
// Printing the output 
console.log(invt_elem);

输出:

[ 6, 8, 10 ]

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