我有1000个品牌的阵列,我想在其中提供快速搜索。因此,当我开始输入ie:“ m”时,我应该得到“ mammut”和“小米”。数组已排序。那么,有人知道不需要遍历整个数组的快速解决方案吗?最好的JavaScript。谢谢
var brands = new Array("arcterix", "mammut", "millet", "ortovox", ... )
function search(brands, substring){
// will return array of founded brands which begins on substring
}
答案 0 :(得分:2)
尝试一下
var brands = ["arcterix", "mammut", "millet", "ortovox"]
function search(brands, substring){
return brands.filter( i => i.startsWith(substring) )
}
console.log(search(brands, 'm')) // ['mammut', 'millet']
这非常快。快做事几乎是不可能的,一切都为您优化。