使用地图()与具有一个额外的参数的函数的JS回调 [英] JS callback using map() with a function that has one additional parameter

查看:105
本文介绍了使用地图()与具有一个额外的参数的函数的JS回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种方法,使用具有一个额外的参数的更多功能用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清洁瓦特/摆脱这些!

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) {doOpSingle2(a,theFlag);});

这篇关于使用地图()与具有一个额外的参数的函数的JS回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆