试图通过字符串数组一个模式用户输入搜索 - 的JavaScript [英] Trying to search through array of strings for a pattern the user inputs - javascript
问题描述
var p = ["array of words", "i really hate the sun", "i'm TIred"]
function findword(contents,pattern){
var answer;
var idx;
var counter = 0;
var pat_lc = pattern.toLowerCase();
for (var i = 0; i <= contents.length-1; i++){
var str_lc = contents[i].toLowerCase();
idx = str_lc.indexOf(pat_lc)
if (idx >= 0){
answer = i
}
else{
answer = "-1"
}
}
alert(answer)
}
findword(p,"words")
我试图找到数组的某个字在字符串数组的索引,但它仅适用于上述阵列中的某些词。例如,在code的最后一行,当我选择要搜索词返回答案和IDX-1的值时,应分别0和9。然而,当我搜索累,答案的值为2,IDX为4(这是正确的)。有些话为什么工作和其他人返回值-1?
I'm trying to find the index of the array for a certain word, in an array of strings, however it only works for certain words in the array above. For example, on the last line of the code, when I chose to search for "words" it returns the value of "answer" and "idx" -1 when it should be 0 and 9 respectively. However, when I search for "tired", the value of "answer" is 2 and "idx" is 4 (which is correct). Why do some words work and others return the value of -1?
推荐答案
您应该尽快停止,你找到一个解决方案。
You should stop as soon as you find a solution.
您的程序,只有当它遍历整个数组停止。但是,如果答案是什么不是在最后一个元素?然后答案
将包含 1
。
Your program only stops when it iterated over the whole array. But what if the answer what not in the last element ? Then answer
will contain -1
.
您可以在 1
的init 答案
并继续你的循环
只要 I
小于 content.length
和答案
等于 1
: http://jsfiddle.net/#&togetherjs=dbVcN8JkKP
You can init answer
at -1
and continue your for loop
as long as i
is less than content.length
and answer
is equal to -1
: http://jsfiddle.net/#&togetherjs=dbVcN8JkKP
这篇关于试图通过字符串数组一个模式用户输入搜索 - 的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!