這一定很簡單,但我無法弄清楚如何計算一系列事物中的子串數量。 Underscore中的任何內容爲此我缺少?在Javascript或Underscore中,我可以計算一個數組中子字符串的多少個實例嗎?
var foo = ["fred", "ted", "medical", "car"]
function howManySubstringsInArray(arr, word){
var i = arr.length,
j = 0;
while (i) if (arr[--i].indexOf(word))++j;
return j;
}
howManySubstringsInArray(foo, 'ed')
Output => 3
這是行不通的。
檢出:http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string –
它應該匹配一個字中的多個子字符串嗎? – loganfsmyth
你應該使用'arr [ - i] .indexOf(word)!= -1' – jcubic