使用带有一个附加参数的函数的 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/地图
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.您可能想要对其进行 OR 的标志(想想位掩码)
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!
当然,任何解决方案都应该不用 for
循环,因为这就是我们有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屋!