2011-11-04 23 views
1

我試圖通過數組循環來檢查特定的模式,但之後不再輸出。不知道我做錯了什麼!我將不勝感激任何幫助!循環遍歷數組以檢查模式

我正在測試模式或帽子。

sample = ["cat fat hat mat", "that the who"] 
searchTerm = prompt("Testing?"); 

function count(sample, searchTerm) 
{ 

    for (i=0;i<sample.length;i++) 
    { 
    if (sample[i].indexOf(searchTerm) == -1) 
    { 
     return 0; 
    } 
    return count(sample.substring(sample.indexOf(searchTerm) + searchTerm.length), searchTerm) + 1; 
    } 
} 

alert(count(sample, searchTerm)); 

改頭換面代碼

search = ["cat fat hat mat", "that the who"]; 

var pattern = prompt('Search?'); 

function count(sample, searchTerm) 
{ 
    var count, i; 
    count = 0; 
    for (i=0; i < sample.length; i++) 
    { 
     if (sample[i].indexOf(searchTerm) !== -1) 
     { 
      count++; 
     } 
    } 
    return count; 
} 

count(search, pattern); 

我重做一切,它仍然沒有給出輸出。

+0

什麼模式,你的測試?總體目標是什麼? – Polynomial

+0

我正在測試「at」模式。 – methuselah

+1

你需要使用一個alert()或其他的東西來顯示你的'rehashed'代碼中的結果。 –

回答

2

這段代碼有幾個問題。最直接的一種是您撥打substringarray而不是string

return count(sample.substring ... 

有可能你的意思是說

return count(sample[i].substring ... 

的第二個問題是,雖然你需要劃分邏輯了一下。你需要將它分成幾個部分,這些部分計算一個單詞中的出現次數以及通過該數組迭代的次數。今天,他們相互交織,因爲你最終通過非陣列地方期待陣列

function count(sample, searchTerm) { 
    var num = 0; 
    for (i=0;i<sample.length;i++) { 
    var current = sample[i]; 
    var index = current.indexOf(searchTerm); 
    while (index >= 0) { 
     num++; 
     index = current.indexOf(searchTerm, index + 1); 
    } 
    } 
    return num; 
} 

工作小提琴導致奇怪的行爲:http://jsfiddle.net/wrNbL/

+0

我設法在這裏完成了一些事情[link(http://jsfiddle.net/CnREL/),但是當我把它裹在一個for循環中,它可怕地失敗了! – methuselah

+0

@jeansymolanza檢查我剛剛發佈到我的答案的小提琴鏈接。它有一個工作示例 – JaredPar

+0

完美謝謝! – methuselah

2

您不需要在這裏使用遞歸,只要在搜索項匹配時重複遍歷數組。

function count(sample, searchTerm) 
{ 
    var count, i; 
    count = 0; 
    for (i=0; i < sample.length; i++) 
    { 
     if (sample[i].indexOf(searchTerm) !== -1) 
     { 
      count++; 
     } 
    } 
    return count; 
} 
+0

如果一個特定模式有多個匹配項會怎麼樣?它會計算一切嗎? – methuselah

+0

不,這隻會計算包含searchTerm的數組中元素的數量。 –

+0

我該如何計算每個數組中的模式數量,就像我在這裏所做的那樣:http://jsfiddle.net/CnREL/ – methuselah