使用上下文

时间:2016-06-15 00:20:43

标签: javascript pointers underscore.js

我无法理解_.filter()函数在unfcorejs中是如何工作的。具体来说,我试图了解是否有办法从被过滤的对象返回值,而不是索引。

假设如下:

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)

哪会返回[false,false,false,false,true,false,true]。我知道_.filter()在内部调用_.each()来处理数组。因此,_.filter([0,1,2,3,4,5,6], function(x) { return this[x] % 5 == 0 ;}, A)的调用无效,因为_.each()调用未在其函数中接收this[x]值,因此这是有意义的。

我只是遗漏了一些东西,或者没有办法调用将返回值的_.filter()?

1 个答案:

答案 0 :(得分:2)

Somethisng喜欢这个?:

var indexes = [0,1,2,3,4,5,6];
_.filter(A, function(x, i) {
    return x % 5 == 0 && indexes.indexOf(i) > -1;
});

enter image description here