JavaScript:考虑字母顺序的搜索栏



这是我在stackOverflow的第一篇帖子(请不要做怪物,呵呵(。我正在为搜索栏的功能寻找建议或提示。我已经在使用这个:

for (i = 0; i < taskButton.length; i++) {
//if there is a match 
if (tasks[i].toUpperCase().indexOf(filter) > -1) {
//display the match
taskButton[i].style.display = "";
} else {
//hide the mismatch
taskButton[i].style.display = "none";
}
}

但是对于indexOf,字符串中是否有空格字符,例如,它将显示所有带有空格的字符串。考虑到每个字母的顺序,我想改进这个搜索功能。谢谢各位先遣队员!

使用startsWith而不是indexOf:

for (let i = 0; i < taskButton.length; i++) {
taskButton[i].style.display = tasks[i].toUpperCase().startsWith(filter)
? ''
: 'none';
}

如上所述,您可以使用条件运算符使代码更加简洁,还可以确保声明i变量-如果您不声明变量,您将隐式分配给全局对象(这是混乱的(,,如果您处于严格模式,则会引发错误。

最新更新