This code is to be integrated into an AJAX Chat system to enable a tab auto-completion of user names:
var usernames = new Array();
usernames[0] = "Saladin";
usernames[1] = "Jyllaby";
usernames[2] = "CadaverKindler"开发者_JAVA百科;
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]);
A couple of notes to be made: The array of usernames and the text variable would both be loaded from the chat itself via AJAX (which, unfortunately, I don't know), and the final output will be handled by AJAX as well.
Is there a more efficient way to do this?
Also, any tips on how to handle multiple instances of the searchTerm being found?
Micro-optimization: instead of getting the substring and comparing it (creating lots of temporary strings)...
usernames[i].substr(0,searchTerm.length) != searchTerm
...you should use indexOf, which creates no temporary strings...
usernames[i].indexOf(searchTerm) == 0
What do you mean by "multiple instances of the searchTerm being found"? Can you give an example of the problem you're thinking of?
You can make this significantly more efficient (provided large number of users) by keeping the array sorted and using binary search to find the match.
The way you have it coded now:
for(i = 0; i < usernames.length && usernames[i].substr(0,searchTerm.length) != searchTerm; i++);
You are checking the length of usernames and the length of searchTerm as well as getting a substr from usernames[i] EVERY time the loop uh, loops.
For any of these that you don't expect to change during the course of the loop, you should store them in a variable before the loop starts.
Getting a value out of a variable is much faster than checking an object property or method.
So something like:
for(i = 0,ii=usernames.length,j=searchTerm.length; i < ii && usernames[i].substr(0,j) != searchTerm; i++);
精彩评论