[英]underscore.js filter function using context
我在了解_.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)
這將返回[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)
調用沒有_.filter([0,1,2,3,4,5,6], function(x) { return this[x] % 5 == 0 ;}, A)
無法工作,因為_.each()調用未在其函數中接收到this[x]
值。
我是否只是缺少某些東西,還是沒有辦法調用_.filter()來返回值?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.