此代码将集成到 AJAX 聊天系统中,以启用选项卡自动完成用户名:
var usernames = new Array();
usernames[0] = "Saladin";
usernames[1] = "Jyllaby";
usernames[2] = "CadaverKindler";
usernames[3] = "qbsuperstar03";
var text = "Text and something else q";
// Start of the script to be imported
var searchTerm = text.slice(text.lastIndexOf(" ") + 1);
var i;
for(i = 0; i < usernames.length && usernames[i].substr(0,searchTerm.length) != searchTerm; i++);
// End of the script to be imported
document.write(usernames[i]);
需要注意的几点:用户名数组和文本变量都将通过 AJAX 从聊天本身加载(不幸的是,我不知道),最终输出将由 AJAX 处理也是如此。
有没有更有效的方法来做到这一点?
另外,关于如何处理找到的 searchTerm 的多个实例,有什么建议吗?
最佳答案
微优化:而不是获取子字符串并进行比较(创建大量临时字符串)...
usernames[i].substr(0,searchTerm.length) != searchTerm
...您应该使用indexOf,它不会创建临时字符串...
usernames[i].indexOf(searchTerm) == 0
“找到多个 searchTerm 实例”是什么意思?您能举例说明您正在考虑的问题吗?
关于javascript - 有什么方法可以让这个 JavaScript 选项卡补全脚本更加高效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2770052/