使用带有两个参数的函数的javascript映射

Cur*_*arn 49 javascript

我知道我可以用map以下方式使用一个变量的函数:

var squarefunc = function(x) {
    return x*x;
};
values = [1,2,3,4]
values.map(squarefunc) // returns [1,4,9,16]
Run Code Online (Sandbox Code Playgroud)

如何使用map以下功能:

var squarefuncwithadjustment = function(x, adjustment) {
    return (x*x + adjustment);
}
Run Code Online (Sandbox Code Playgroud)

其中,我想adjustment在调用map时手动输入参数值,比如说adjustment=2,并且x从数组中获取值values.

cas*_*nca 85

使用匿名函数:

values.map(
  function(x) { return squarefuncwithadjustment(x, 2); }
);
Run Code Online (Sandbox Code Playgroud)


Pet*_*ter 40

您可以使用回调创建功能:

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]
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案解决了将辅助参数传递给map-reduce链的更广泛问题,因此得到了我的投票. (5认同)
  • 谢谢彼得.我喜欢这个解决方案.我一直试图进入中级JS级别.这是一种涂料语言 (2认同)

Dim*_*dov 17

从ES6开始,您可以使用:

.map((element) => func(element,params...))
Run Code Online (Sandbox Code Playgroud)

在你的情况下,如果我想使用3作为调整:

values = [1,2,3,4]
values.map(n => squarefuncwithadjustment(n,3))
Run Code Online (Sandbox Code Playgroud)


gra*_*ing 7

如果颠倒参数的顺序,可以将调整绑定为第一个参数,以便x将其作为第二个参数传递.

var squarefuncwithadjustment = function(adjustment, x) {
    return (x*x + adjustment);
}

values.map(squarefuncwithadjustment.bind(null, 2)); // [3, 6, 11, 18]
Run Code Online (Sandbox Code Playgroud)

.bind设置调用上下文的第一个参数,这里没关系,所以我使用了null.第二个参数.bind绑定2为调用时的第一个参数.

将函数存储为绑定版本可能更好.

var squareFuncWith2 = squarefuncwithadjustment.bind(null, 2);
Run Code Online (Sandbox Code Playgroud)

然后用它.map.

values.map(squareFuncWith2); // [3, 6, 11, 18]
Run Code Online (Sandbox Code Playgroud)


aja*_*mar 5

好!!您可以轻松地将第二个参数传递给 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;
});
Run Code Online (Sandbox Code Playgroud)

或者

var adjustment = 1;
var squarefunc = function(x , adjustment) {
    return x*x + adjustment;
};
values = [1,2,3,4]
values.map(squarefunc);
Run Code Online (Sandbox Code Playgroud)