我知道我可以用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)
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)
如果颠倒参数的顺序,可以将调整绑定为第一个参数,以便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)
好!!您可以轻松地将第二个参数传递给 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)
归档时间: |
|
查看次数: |
47261 次 |
最近记录: |