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

Using javascript map with a function that has two arguments

本文关键字:参数 两个 函数 映射 javascript      更新时间:2023-09-26

我知道我可以用以下方式将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);
}

其中,当我调用映射(比如adjustment=2)时,我想手动输入参数adjustment的值,并且x的值取自数组values

使用匿名函数:

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]

从ES6开始,您可以使用:

.map(element => fn(element, params))

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

values = [1,2,3,4]
values.map(n => squarefuncwithadjustment(n, 3))

如果颠倒参数的顺序,可以将调整绑定为第一个参数,这样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;
});

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

要在单个函数中执行此操作,您可以在Curry中添加短划线IIFE。

function mapSingleFunc(values, adjustment) {
  return values.map((adjustment => x => (x * x) + adjustment)(adjustment));
};
console.log(mapSingleFunc([1,2,3,4], 2))

从最抽象的意义上讲,您可以通过调用数组来隧道传输values。通过添加IIFE,您可以在闭包中的每个时间向中提供adjustment

ES6+:

values.map( x => squarefuncwithadjustment(x,2) );

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

然后

values = values.map( x => squarefuncwithadjustment(x, 2) );