Lodash _.ternary() 方法
Lodash 是一个基于 underscore.js 的 JavaScript 库。 Lodash 有助于处理数组、字符串、对象、数字等。
_.ternary()方法返回一个只接受三个参数的新函数,并将这些参数传递给给定的函数。给出的任何附加参数都将被丢弃。
句法:
_.ternary( fun )
参数:此方法采用上面列出并在下面讨论的单个参数:
- fun:这是应该用于参数的函数。
返回值:此方法返回一个新函数。
注意:此方法在普通 JavaScript 中不起作用,因为它需要安装 Lodash contrib 库。可以使用npm install lodash-contrib –save 安装 lodash- contrib 库
示例 1:
Javascript
// Defining lodash contrib variable
var _ = require('lodash-contrib');
// Function to be used
function fun() {
return arguments;
}
// Making the ternary function
var gfgFunc = _.ternary(fun);
console.log("Arguments are :",
gfgFunc("first", "second", "third"));
Javascript
// Defining lodash contrib variable
var _ = require('lodash-contrib');
// Function to be used
function fun() {
return arguments;
}
// Making the ternary function
var gfgFunc = _.ternary(fun);
// Arguments more than 3 are excluded
console.log("Arguments are :",
gfgFunc("a", "b", "c", "d", "e", "f"));
Javascript
// Defining lodash contrib variable
var _ = require('lodash-contrib');
// Function to be used
function add() {
s = 0;
for (i = 0; i < 3; i++) {
s += arguments[i];
}
return s;
}
// Making the ternary function
var gfgFunc = _.ternary(add);
// Arguments more than 3 are excluded
console.log("Sum of first 3 arguments is :",
gfgFunc(100, 100, 1000, 4, 5, 6, 7));
输出:
Arguments are : [Arguments]
{ '0': 'first', '1': 'second', '2': 'third' }
示例 2:
Javascript
// Defining lodash contrib variable
var _ = require('lodash-contrib');
// Function to be used
function fun() {
return arguments;
}
// Making the ternary function
var gfgFunc = _.ternary(fun);
// Arguments more than 3 are excluded
console.log("Arguments are :",
gfgFunc("a", "b", "c", "d", "e", "f"));
输出:
Arguments are : [Arguments] { '0': 'a', '1': 'b', '2': 'c' }
示例 3:在此示例中,我们将添加参数,但只有前 3 个参数将使用此方法。
Javascript
// Defining lodash contrib variable
var _ = require('lodash-contrib');
// Function to be used
function add() {
s = 0;
for (i = 0; i < 3; i++) {
s += arguments[i];
}
return s;
}
// Making the ternary function
var gfgFunc = _.ternary(add);
// Arguments more than 3 are excluded
console.log("Sum of first 3 arguments is :",
gfgFunc(100, 100, 1000, 4, 5, 6, 7));
输出:
Sum of first 3 arguments is : 1200