返回从'for'循环在Javascript中的所有值

问题描述:

for (var i = 0; i < dataSets.length; i++) { 
     var result = _.filter(data, function(item){ 
      return _.contains(item, dataSets[i]); 
     }); 
     var collection = [] 
     for(x in result)collection.push(result[x].value); 
    } 

当我在方法内部执行console.log(collection)时,可以看到3个数组,这是正确的。返回从'for'循环在Javascript中的所有值

[431, 552, 318, 332, 185] 
[17230, 17658, 15624, 16696, 9276] 
[5323, 6359, 8216, 9655, 5513] 

但是在方法之外,我只能得到最后一个值。

[5323, 6359, 8216, 9655, 5513] 

有没有一种方法,我可以返回的方法之外所有值是多少?

+0

定义外部“collectionArray”(的为范围)然后将集合推入。或者使用dataSets的map函数,假设它是一个数组,并且您使用的是相对较新的浏览器) – 2015-02-23 23:35:55

+0

您的集合[]数组在每次迭代for ...循环时被覆盖,因此将其移出for ...循环并且它应该工作.. – 2015-02-23 23:37:22

+0

不要使用['for in' loops](http://*.com/q/500504/1048572)! – Bergi 2015-02-23 23:52:06

可以每个集合添加到一个数组:

var collections = []; 
for (var i = 0; i < dataSets.length; i++) { 
    var result = _.filter(data, function(item){ 
     return _.contains(item, dataSets[i]); 
    }); 
    collections[i] = []; 
    for(x in result) collections[i].push(result[x].value); 
} 
// Now you have all values into "collections" 
// If you are within a method you can also "return collections;" here 
+0

呃这是一个漫长的夜晚,谢谢! – Jess 2015-02-23 23:50:13

如果你记得的ES6状态是:

dataSets . map(set => data . 
    filter(item => item.contains(set)) . 
    map (item => item.value) 
)