使用带有两个参数的函数的javascript映射
我知道我可以通过以下方式将使用带有两个参数的函数的javascript映射,javascript,Javascript,我知道我可以通过以下方式将map与一个变量的函数一起使用: var squarefunc = function(x) { return x*x; }; values = [1,2,3,4] values.map(squarefunc) // returns [1,4,9,16] 如何通过以下功能使用map: var squarefuncwithadjustment = function(x, adjustment) { return (x*x + adjustment); }
map
与一个变量的函数一起使用:
var squarefunc = function(x) {
return x*x;
};
values = [1,2,3,4]
values.map(squarefunc) // returns [1,4,9,16]
如何通过以下功能使用map
:
var squarefuncwithadjustment = function(x, adjustment) {
return (x*x + adjustment);
}
values.map(
function(x) { return squarefuncwithadjustment(x, 2); }
);
var createSquareFuncWithAdjustment = function(adjustment) {
return function(x) { return (x * x) + adjustment; };
};
values = [1, 2, 3, 4];
values.map(createSquareFuncWithAdjustment(2)); // returns [3, 6, 11, 18]
其中,我想在调用map时手动输入参数
adjustment
的值,比如adjustment=2
,并从数组values
中获取x
的值使用匿名函数:
var squarefuncwithadjustment = function(x, adjustment) {
return (x*x + adjustment);
}
values.map(
function(x) { return squarefuncwithadjustment(x, 2); }
);
var createSquareFuncWithAdjustment = function(adjustment) {
return function(x) { return (x * x) + adjustment; };
};
values = [1, 2, 3, 4];
values.map(createSquareFuncWithAdjustment(2)); // returns [3, 6, 11, 18]
您可以使用回调创建函数:
var squarefuncwithadjustment = function(x, adjustment) {
return (x*x + adjustment);
}
values.map(
function(x) { return squarefuncwithadjustment(x, 2); }
);
var createSquareFuncWithAdjustment = function(adjustment) {
return function(x) { return (x * x) + adjustment; };
};
values = [1, 2, 3, 4];
values.map(createSquareFuncWithAdjustment(2)); // returns [3, 6, 11, 18]
如果颠倒参数的顺序,可以将调整绑定为第一个参数,以便将
x
作为第二个参数传递
var squarefuncwithadjustment = function(adjustment, x) {
return (x*x + adjustment);
}
values.map(squarefuncwithadjustment.bind(null, 2)); // [3, 6, 11, 18]
.bind
的第一个参数设置调用上下文,这在这里并不重要,因此我使用了null
。调用时,.bind
的第二个参数将2
绑定为第一个参数
最好将函数存储为绑定版本
var squareFuncWith2 = squarefuncwithadjustment.bind(null, 2);
然后将其与.map
一起使用
values.map(squareFuncWith2); // [3, 6, 11, 18]
嗯!!您可以轻松地将第二个参数传递给map函数。以下方法广泛用于传递此参数,此参数通常在调用过程中隐藏:
values.map(function(x , this) {
return x*x + this.adjustment;
});
var adjustment = 1;
var values = [1,2,3,4]
values.map(function(x , adjustment) {
return x*x + adjustment;
});
或
从ES6开始,您可以使用:
.map((element) => func(element,params...))
在您的情况下,如果我想使用3作为调整:
values = [1,2,3,4]
values.map(n => squarefuncwithadjustment(n,3))
var squarefuncwithadjustment=(x,adjustment)=>{
返回(x*x+调整);
}
然后
values=values.map(
x=>squarefuncwithadjustment(x,2)
);代码>要在单个功能中执行此操作,您可以在咖喱中添加少量生命
函数mapSingleFunc(值、调整){
返回值.map((调整=>x=>(x*x)+调整)(调整));
};
log(mapSingleFunc([1,2,3,4],2))
ES6+:
values.map( x => squarefuncwithadjustment(x,2) );
这是一个解决方案,它解决了将辅助参数传递给map reduce链的更广泛的问题,因此得到了我的投票。@Sridhar Sarnobat这是一个闭包的例子吗?@Courtney我从来没有完全弄清楚闭包是什么,“但是我猜答案是肯定的。”Courtney JavaScript中的每个函数都会在定义它的范围内关闭。在此特定情况下,内部匿名函数保留对调整参数的访问。这将启动承诺,而不是将其保存为promise.all()。我如何以声明的方式设置和使用承诺?