Underscore.js _.binary() 方法
Underscore.js _.binary()方法返回一个只接受两个参数的新函数,并将这些参数传递给给定的函数。其他参数被丢弃。
句法:
_.binary( fun )
参数:此方法采用上面列出并在下面讨论的单个参数。
- fun:这是给定的函数。
返回值:它返回一个新函数。
注意:要执行以下示例,您必须使用此命令提示符安装underscore-contrib库并执行以下命令。
npm install underscore-contrib
示例 1:
Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib');
// Function
function fun(){
var mul = 1;
for (var i = 0; i < arguments.length; i++) {
mul = mul * arguments[i];
}
return mul;
}
var gfgFunc = _.binary(fun);
console.log("Multiplication is :",
gfgFunc(2,3));
Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib');
// Function
function fun() {
var mul = 1;
for (var i = 0; i < arguments.length; i++) {
mul = mul * arguments[i];
}
return mul;
}
var gfgFunc = _.binary(fun);
// Only operates for first two parameters
console.log("Multiplication is :",
gfgFunc(2,23,2,2));
Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib');
// Function
function fun() {
return arguments;
}
var gfgFunc = _.binary(fun);
// Only first two parameters will
// be used as arguments
console.log("Binary Arguments are :",
gfgFunc("a", "b", "c", "d", "e"));
输出:
Multiplication is : 6
示例 2:
Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib');
// Function
function fun() {
var mul = 1;
for (var i = 0; i < arguments.length; i++) {
mul = mul * arguments[i];
}
return mul;
}
var gfgFunc = _.binary(fun);
// Only operates for first two parameters
console.log("Multiplication is :",
gfgFunc(2,23,2,2));
输出:
Multiplication is : 46
示例 3:
Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib');
// Function
function fun() {
return arguments;
}
var gfgFunc = _.binary(fun);
// Only first two parameters will
// be used as arguments
console.log("Binary Arguments are :",
gfgFunc("a", "b", "c", "d", "e"));
输出:
Binary Arguments are : [Arguments] { '0': 'a', '1': 'b' }