2014-10-17 41 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