Return 来自 'for' 的所有值在 Javascript 中循环

Return all values from 'for' loop in 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 个数组,这是正确的。

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

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

[5323, 6359, 8216, 9655, 5513]

有什么方法可以 return 所有 方法之外的值吗?

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

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

如果您处于 ES6 心态:

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