我有一个由几个单词组成的数组,我找到了一个特定的单词.我目前的解决方案,如下所示,适用于小阵列.但是如果这个数组包含10,000个单词,那么我的解决方案需要大量的内存和CPU资源,因为它不够高效.如何在性能方面使代码更好,并且在JavaScript中为大型数组占用更少的资源?
var words = ['apple', 'orange', 'ananas', 'banana', 'mango', 'lemon', 'tomato'];
function search (term) {
for (var i = 0, len = words.length; i < len; i++) {
if (words[i] === term) {
console.log(words[i] + ' is found at ' + i);
}
}
}
search('tomato');
Run Code Online (Sandbox Code Playgroud)
小智 6
使用单词作为键预填充字典(对象).然后查找只是dict[term].
var words = ['apple', 'orange', 'ananas', 'banana', 'mango', 'lemon', 'tomato'];
var dict = {};
function prepopulate() {
words.forEach(function(word, i) { dict[word] = i; });
}
function search (term) {
if (term in dict) {
console.log(term + ' is found at ' + dict[term]);
}
}
prepopulate();
search('tomato');
Run Code Online (Sandbox Code Playgroud)