我无法理解 _.filter() 函数在 undescorejs 中的工作原理。具体来说,我试图了解是否有一种方法可以从被过滤的对象返回值,而不是索引。
假设如下:
var A = [1,2,3,4,5,8,10,12,15,20,25,30];
现在有了标准实现:
_.filter(A, function(x) { return x % 5 == 0 ;})
这将返回 [5,10,15,20,25,30]。我的问题如下:
_.filter([0,1,2,3,4,5,6], function(x) { return this[x] % 5 == 0 ;}, A)
这将返回 [4,6],它们是真实值的索引(可被 5 整除的值)。但我想从原始数组返回真实索引的值,即 [5,10]。
根据我对其他 underscore.js 函数(例如 _.each() 和 _.map())的理解,这就是我使用上下文调用该函数的方式。
_.map([0,1,2,3,4,5,6], function(x) { return this[x] % 5 == 0 ; }, A)
这将返回[假,假,假,假,真,假,真]。我知道 _.filter() 正在内部调用 _.each() 来处理数组。所以我的调用 _.filter([0,1,2,3,4,5,6], function(x) { return this[x] % 5 == 0 ;}, A )
不起作用,因为 _.each() 调用没有在其函数中接收 this[x]
值。
我只是错过了一些东西还是没有办法调用 _.filter() 来返回值?
最佳答案
像这样的东西吗?:
var indexes = [0,1,2,3,4,5,6];
_.filter(A, function(x, i) {
return x % 5 == 0 && indexes.indexOf(i) > -1;
});
关于javascript - underscore.js 使用上下文的过滤函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37824204/