使用带有两个参数的函数的 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 (比如说 adjustment=2)时手动输入参数 adjustment的值,并从数组 values中获取 x的值。

101996 次浏览

Use an anonymous function:

values.map(
function(x) { return squarefuncwithadjustment(x, 2); }
);

You could use a callback creation function:

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]

If you reverse the order of your arguments, you can bind the adjustment as the first argument, so that the x will be passed as the second.

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


values.map(squarefuncwithadjustment.bind(null, 2)); // [3, 6, 11, 18]

The first argument to .bind sets the calling context, which doesn't matter here, so I used null. The second argument to .bind binds 2 as the first argument when invoked.

It may be better to store the function as a bound version.

var squareFuncWith2 = squarefuncwithadjustment.bind(null, 2);

Then use it with .map.

values.map(squareFuncWith2); // [3, 6, 11, 18]

Well!! You can easily pass a second parameter to the map function. The following method is widely used to pass this parameter which generally gets hidden during the call:

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;
});

OR

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

As of ES6 you can use:

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

In your case if I want to use 3 as adjustment:

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

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

Then

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

To perform this within a single function, you can add a dash of IIFE to your Curry.

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

In the most abstract sense you are able to tunnel your values in through the calling array. Adding an IIFE allows you to feed the adjustment in each time in the closure.

ES6+ :

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