使用map()的JS回调函数具有一个附加参数 [英] JS callback using map() with a function that has one additional parameter
问题描述
我试图找到一种使用JS的 Array.prototype.map()
功能的方法,其功能还包含一个附加参数(如果可能的话)我想避免不得不重写内置的 Array.prototype.map()
)。
本文档非常好,但不涵盖一个或多个附加参数的情况:
I'm trying to find a way to use JS's Array.prototype.map()
functionality with a function that has one additional parameter more (if possible at all, and I'd like to avoid having to rewrite built-in Array.prototype.map()
).
This documentation is very good, but does not cover the "one-or-more-additional-parameter" case:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map
function doOpSingle(elem)
{
// do something with one array element
}
var A = ["one", "two", "three", "four"];
var x = A.map(doOpSingle); // this will execute doOpSingle() on each array element
到目前为止,这么好。
但是如果有问题的函数有两个参数,如e。 G。一个你可能想要的旗子(想想一下面具)
So far, so good. But what if the function in question has two parameters, like e. g. a flag you might want to OR to it (think of bit masks)
function doOpSingle2(arrelem,flag)
{
// do something with one array element
}
var A = ["one", "two", "three", "four"];
var theFlag = util.getMask(); // call external function
var y = A.map(doOpSingle2(theFlag)); // this does not work!
任何解决方案都应该没有 code>循环,当然,因为这就是为什么我们有
map()
,使我们的代码更清洁,摆脱这些!
Any solutions should do without for
loops, of course, because that's why we have map()
, to make our code cleaner w/getting rid of these!
推荐答案
使用匿名函数:
A.map(function(a) {return doOpSingle2(a,theFlag);});
这篇关于使用map()的JS回调函数具有一个附加参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!