在搜索数组中的匹配项时优化javascript代码 [英] Optimize javascript code on searching for matches in array
问题描述
基本上,我需要从数组中获取包含在主字符串中的单词
Basically, I need to get the words from the array which are contained in the main string
我在这里有一个循环代码,但我认为有一个单一的代码可以完成这个任务. 我不仅需要对代码长度进行优化,还需要对性能进行优化.
I have a looping code here but I think there is a one-liner to do the trick. I need the code to be optimized not only in code length but also in performance.
谢谢
var aValidWords = ["ex", "exes", "expert",
"experts", "expertise", "sex", "sexes",
"exchange", "change", "changes"];
var sMainWord = "expertsExchange";
var aPossibleWords = new Array();
var sMainWordLower = sMainWord.toLowerCase();
for(i=0; i < aValidWords.length; i++){
var sCurrentWord = aValidWords[i].toLowerCase();
if(sMainWordLower.indexOf(sCurrentWord) != -1){
aPossibleWords.push(aValidWords[i]);
}
}
document.write(aPossibleWords.join("<br />"));
推荐答案
我认为您的代码很不错.
I think your code is decent.
如果您真的很担心性能,则可能需要尝试一些复杂的方法,例如 http://en.wikipedia.org/wiki/String_searching_algorithm#Single_pattern_algorithms
If you're really worried about performance, you may want to try some sophisticated method like Boyer-Moore. But, if you just have a handful of patterns and relatively short strings, then the initialization overhead is higher than the benefit, so you should stick with the simple approach. See Wikipedia's comparison table http://en.wikipedia.org/wiki/String_searching_algorithm#Single_pattern_algorithms
这篇关于在搜索数组中的匹配项时优化javascript代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!