2013-02-19 71 views
1

這個Javascript地圖功能的工作原理我的地圖功能的罰款外:貓鼬的MapReduce:使用array.some

var cribs = ["list","tree"]; 

if (cribs.some(function(i){return (new RegExp(i,'gi')).test("a long list of words");})) { 
console.log('match'); 
} 

(它只是搜索與值的字符串從一個數組)。

雖然使用它在我的地圖功能不起作用:

var o = {}; 
o.map = function() { 
    if (cribs.some(function(i){return (new RegExp(i,'gi')).test(this.name);})) { 
     emit(this, 1) ; 
    } 
} 
o.out = { replace: 'results' } 
o.verbose = true; 
textEntriesModel.mapReduce(o, function (err, model, stats) { 
    model.find(function(err, data){ 
     console.log(data); 
    }); 
}) 

它不排放任何東西,所以我有一個空的結果集。沒有錯誤。

如果我不使用array.some,而不是我只是用一個簡單的正則表達式,然後正常工作:

o.map = function() { 
    if(this.name.match(new RegExp(/list/gi))) { 
     emit(this, 1) ; 
    } 
} 

所以我的問題是,爲什麼不array.some功能上述工作在我的地圖功能?

我有一長串單詞,我需要匹配,所以我真的不想爲他們單獨編寫正則表達式,其中上述應該工作。

這裏是我想在我的地圖功能,使用該功能的的jsfiddle:http://jsfiddle.net/tnq7b/

回答

3

你需要讓cribs提供給map功能通過將其添加到scope選項:

var cribs = ["list","tree"]; 
var o = {}; 
o.map = function() { 
    if (cribs.some(function(i){return (new RegExp(i,'gi')).test(this.name);})) { 
     emit(this, 1); 
    } 
} 
o.out = { replace: 'results' }; 
o.scope = { cribs: cribs }; 
o.verbose = true; 
textEntriesModel.mapReduce(o, function (err, model, stats) { 
    model.find(function(err, data){ 
     console.log(data); 
    }); 
});