Underscore.js _.mapArgsWith() 方法
_.mapArgsWith()方法接受一个映射函数并返回一个新的组合函数,该函数将接受一个目标函数并返回一个新函数,该函数在执行目标函数的主体之前将其参数与映射函数进行映射。
句法:
_.mapArgsWith( mapping_function );
参数:
- mapping_function:要被函数。
返回值:此方法返回一个函数。
注意:这在普通 JavaScript 中不起作用,因为它需要安装 underscore.js contrib 库。
underscore.js contrib 库可以使用npm install underscore-contrib –save 安装。
示例 1:我们创建了一个函数,该函数将给定值取立方,然后将该值添加到自身。
Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib');
function add (x) {
return x + x + x ;
}
function sub (x) {
return x - 2;
}
var addnow = _.mapArgsWith(sub);
var subnow = addnow(add);
console.log(subnow(5))
Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib');
function squ (x) {
return x * x ;
}
function add (x) {
return x + 10;
}
var addnow = _.mapArgsWith(add);
var sq = addnow(squ);
console.log(sq(5))
Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib');
function cs (x) {
return
"GeeksforGeeks : Computer Science Portal for Geeks";
}
function geek (x) {
return "GeeksforGeeks";
}
var gfg = _.mapArgsWith(geek);
var gfgFunc = gfg(cs);
console.log(gfgFunc())
Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib');
function cs (x) {
return x;
}
function geek (x) {
return x[0]+" : "+x[1];
}
var gfg = _.mapArgsWith(geek);
var gfgFunc = gfg(cs);
console.log(gfgFunc(["GeeksforGeeks",
"Computer Science Portal for Geeks"]))
输出:
9
示例 2:
Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib');
function squ (x) {
return x * x ;
}
function add (x) {
return x + 10;
}
var addnow = _.mapArgsWith(add);
var sq = addnow(squ);
console.log(sq(5))
输出:
225
示例 3:
Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib');
function cs (x) {
return
"GeeksforGeeks : Computer Science Portal for Geeks";
}
function geek (x) {
return "GeeksforGeeks";
}
var gfg = _.mapArgsWith(geek);
var gfgFunc = gfg(cs);
console.log(gfgFunc())
输出:
GeeksforGeeks : Computer Science Portal for Geeks
示例 4:
Javascript
// Defining underscore contrib variable
var _ = require('underscore-contrib');
function cs (x) {
return x;
}
function geek (x) {
return x[0]+" : "+x[1];
}
var gfg = _.mapArgsWith(geek);
var gfgFunc = gfg(cs);
console.log(gfgFunc(["GeeksforGeeks",
"Computer Science Portal for Geeks"]))
输出:
GeeksforGeeks : Computer Science Portal for Geeks