【问题标题】:How to use async.mapseries with Arrays (Holding arrays)如何将 async.mapseries 与数组一起使用(保存数组)
【发布时间】:2013-12-19 09:10:47
【问题描述】:

我有一个对象:

var sampleArray = [["name1", "age1"], ["name2", "age2"],["name3", "age3"]];

async.mapSeries(sampleArray[names], sampleFunction(), function(err, result) {
  console.log(result);
});//sample code //["name1","name2","name3"] executes here

async.mapSeries(sampleArray[ages], sampleFunction(), function(err, result) {
  console.log(result);
});//sample code //["age1","age2","age3"] executes here

这是我的示例代码,在这里我想实现第一次在 samplefunction 中执行所有“name”属性,并在第二次迭代中实现所有“age”属性。

如何实现?

【问题讨论】:

  • 在您的代码中,对sampleArray[names] 的调用将返回未定义...这是一个您无法通过这种方式访问​​它的数组。
  • @Arno2501 我把这个作为参考,目的是表明我想要那里的名字......

标签: javascript async.js


【解决方案1】:

我想你想要的是这个:

var sampleArray = [["name1", "age1"], ["name2", "age2"],["name3", "age3"]];

async.mapSeries(sampleArray, function(data,callback){
    return callback(null, data[0]);
}, function(err, results) {
    console.log('results : ' + results);  // results : name1,name2,name3  
});
//sample code //["name1","name2","name3"] executes here

async.mapSeries(sampleArray, function(data,callback){
    return callback(null, data[1]);
}, function(err, results) {
    console.log('results : ' + results); // results : age1,age2,age3
});
//sample code //["age1","age2","age3"] executes here

http://jsfiddle.net/9bdWT/12/

编辑对象数据:

var sampleData = [{'name':'name1', 'age':'age1'},{'name':'name2', 'age':'age2'},{'name':'name3', 'age':'age3'}];

async.mapSeries(sampleData, function(data,callback){
    return callback(null, data['name']);
}, function(err, results) {
    console.log('results : ' + results); // results : name1,name2,name3 
});

这样您就可以访问 name 属性而不必担心索引

【讨论】:

  • 好吧明白你的意思,但是如果第一个元素是两个元素的数组,这很好。如果它拥有两个以上的值怎么办,我的意思是我们不知道它拥有多少个值。我的意思是任何通用的方法。例如:如果 sampleArray = [["name1","age1","empcode"....],["name2","age2","empcode"....]] 种模式。我们不确定的地方。元素。
  • 好吧,如果您要使用数组,唯一的方法就是拥有一个索引,没有其他方法。但是您可以尝试使用具有命名属性的对象。你明白我吗?
  • 顺便说一句,如果您的数组中有任意数量的子元素,只要您寻找的索引不移动,它仍然可以工作。
  • 不能完全得到,“使用具有命名属性的对象:”你的意思是我可以传递对象而不是将数组传递给 async.mapSeries?或者你的意思是传递包含对象的数组。 sampleArray = [{name:"abc",age:23}, {name:"def", age: 24}]。哪种方式是对的?
  • 您能否按实际情况展示您的数据(至少是结构)的具体示例。并解释您寻求的最终结果。因为很难猜。
猜你喜欢
  • 2017-04-23
  • 2012-01-20
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-01
  • 2018-04-22
  • 2017-02-25
相关资源
最近更新 更多