2014-10-17 40 views
-1

分裂我有2列:JavaScript的 - 比較2個陣列與空間

sentence [] 
keywords [] 

例如sentence []

sentence [0] = "my car is blue" 
sentence [1] = "the dog is sleeping" 
sentence [2] = "I am in the kitchen" 
sentence [3] = "How are you" 

keywords []

keywords [0] = "my" 
keywords [1] = " " 
keywords [2] = "car" 
keywords [3] = " " 
keywords [4] = "is" 
keywords [5] = " " 
keywords [6] = "blue" 
keywords [7] = "gghcxfkjc" 
keywords [8] = "532jj" 
keywords [9] = "How" 
keywords [10] = " " 
keywords [11] = "are" 
keywords [12] = " " 
keywords [13] = "you" 
keywords [14] = " " 
keywords [15] = "tech" 

因此,舉例來說,我需要檢測到「我的車是藍色的」和「 你好嗎「在keywords陣列。 請注意,關鍵字[]遵循句子的順序。

如何才能繼續比較和檢測這種信息?

[編輯]我需要知道的關鍵字匹配每個詞的索引[] 例如0,1,2,3,4的第一句話9,10,11,12,13爲另一句話。

+0

爲了澄清,句子中的每個單詞都必須匹配關鍵字才能通過真相測試? – 2014-10-17 10:10:32

+0

可能通過遍歷數組,而有一個標誌爲true或false – devqon 2014-10-17 10:10:38

+1

'keywords.join('')。indexOf('sentence-to-check')!== -1'? – techfoobar 2014-10-17 10:11:31

回答

1

所以,你想通過sentence循環,並檢查是否有任何句子在關鍵字中。

這將這樣的伎倆:

// Build a big string of all keywords 
var keyWordLine = keywords.join('').toLowerCase(); // "my car is bluegghcxfkjc532jjHow are you tech" 
// Loop through all sentences 
for(var i = 0; i < sentence; i++){ 
    // Check the current sentence 
    if(keyWordLine.indexOf(sentence[i].toLowerCase()) !== -1){ 
     // sentence is in the keywords! 
    }else{ 
     // sentence is not in the keywords! 
    } 
} 

現在,您將與這些結果做什麼是由你。你可以,例如,建立一個包括只出現在keywords句子的數組:

var keywords = ["my", " ", "car", " ", "is", " ", "blue", "gghcxfkjc", "532jj", "How", " ", "are", " ", "you", " ", "tech"], 
 
    sentence = ["my car is blue", "the dog is sleeping", "I am in the kitchen", "How are you"], 
 
    keyWordLine = keywords.join('').toLowerCase(), 
 
    output = []; 
 
for(var i = 0; i < sentence; i++){ 
 
    if(keyWordLine.indexOf(sentence[i].toLowerCase()) !== -1){ 
 
     output.push(sentence[i]); 
 
    } 
 
} 
 
alert(output);

+0

感謝您的解決方案,但我需要知道關鍵字[]中匹配的每個單詞的索引。例如O,1,2,3,4爲第一句,9,10,11,12,13爲另一句。 – Jose 2014-10-17 10:23:15

+0

然後你應該問這個問題... – Cerbrus 2014-10-17 10:23:46

+0

你是對的。剛編輯我的問題,謝謝! – Jose 2014-10-17 10:30:54

2

只是join的關鍵字,並期待這句話得到的字符串中:

kw = keywords.join("") 
sentence.forEach(function(s) { 
    console.log(s, kw.indexOf(s) >= 0); 
}); 

打印

my car is blue true 
the dog is sleeping false 
I am in the kitchen false 
How are you true 
+0

比我的混亂更清潔:P我會包含IE9 +免責聲明。 – Cerbrus 2014-10-17 10:23:24

+0

@Cerbrus:我懶得寫每一次))隨意編輯它。 – georg 2014-10-17 10:29:17