【问题标题】:Filling an array with an identical function [duplicate]用相同的函数填充数组[重复]
【发布时间】:2014-06-17 17:23:25
【问题描述】:

我正在尝试创建一个函数,该函数返回一个包含 n 个元素的数组,它们都是相同的函数(此数组稍后将用于使用 async 并行调用这些函数) .
我可以轻松地遍历一个数组并将函数添加到每个元素,但想知道我是否可以在一行中使用map

//the function to point to
var double = function(x) {
    return x*2;
};

//this function will create the array - just a filler for a one-liner
var createConsumersArray = function(numOfConsumers) {
    var consumers = (new Array(2)).map(function(x){return double;});
    return consumers;
};

var t = createConsumersArray(2);
console.log(t);     //prints [,]
console.log(t[1](2));   //TypeError: Property '1' of object , is not a function

如果我用常量预先填充数组,map 可以工作,即:

var x = [1,2,3];
console.log(x.map(function(x){return double;})); //prints [ [Function], [Function], [Function] ]
console.log(x[1](2)); //prints 4

如何以最短的方式用相同的函数填充数组?

【问题讨论】:

  • 数学和其他 cpu-bound 任务在 nodeJS 或浏览器中都不是异步的。
  • 我正在使用async.parallel 模拟异步行为,但这些可以根据需要运行无关的线程或进程。

标签: javascript arrays


【解决方案1】:

你必须改变一点。

var createConsumersArray = function(numOfConsumers) {
    var consumers = Array.apply(null, Array(numOfConsumers)).map(function(){return double;});
    return consumers;
};

【讨论】:

【解决方案2】:

这是更多的函数式编程。如果你想用这种风格编程,我建议你看看underscore.js。这是范围函数的示例:

_.range(10);
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

对于您的用例,您会这样做:

_.map(_.range(4), function(num){ return double; });

这是corresponding jsfiddle example

【讨论】:

  • 我通常在我的项目中使用 lodash,而且你的解决方案确实有效,所以 +1。不过,我这次尝试的是纯 JS 解决方案。
  • 我明白了——关于你未来项目的仅供参考——这段代码与 lodash 100% 兼容:lodash.com/docs#rangelodash.com/docs#map
  • 谢谢@Martin。我知道它们的兼容性(事实上,我从下划线开始并过渡到 lodash)。只是在这个特定的项目上,我试图尽量减少外部资源。但你的答案仍然有效。
猜你喜欢
  • 2017-09-15
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-15
  • 1970-01-01
相关资源
最近更新 更多