quote:
Originally posted by matty
By using oEmail alone it is returning the position in the Array (in other words 0). Need to use oEmails[oEmail] to get the email address from the array.
That's exactly why I'd suggest you to stop using such variable names in loops. By naming your iterating variable "oEmail", you'd think that it contains the e-mail address as a string while actually it's just an index. A much more logical name would be something like "nEmail" or "iEmail" or just something as simple as "i".
Also, when you're dealing with arrays, it's much more effective to iterate with an incrementing number over the array length instead of using property enumeration. Looping over properties is fine for plain objects, but for arrays a generic for-loop from 0 to length is
much faster.
Another thing I noticed is that you're checking the amount of contacts on every iteration. This is completely unnecessary and can easily be moved to the top of the function as preliminary check before the actual loop.
My suggestions:
js code:
var oEmails = [
'email1@hotmail.com',
'email2@hotmail.com'
];
function OnEvent_ChatWndReceiveMessage (pChatWnd, sOrigin, sMessage, nMessageKind) {
// Don't do anything when this is not a one-to-one chat.
if ( pChatWnd.Contacts.Count !== 1 ) return sMessage;
// Loop through the e-mails array, the fast way.
for ( var i=0, len = oEmails.length; i < len; ++i ) {
if ( pChatWnd.Contacts.GetContact(oEmails[i]) ) {
return '';
}
}
}
If you really care about speed and performance, you could even use the high-speed reverse while-loop!
js code:
// Loop through the e-mails array, the fastest way.
var i = oEmails.length;
while ( i-- ) {
if (pChatWnd.Contacts.GetContact(oEmails[i])) {
return '';
}
}
Now, this was already pretty fast, but we can go even faster. Instead of bothering the script engine with a call to GetContact() every time, we can first retrieve the e-mail address we're looking for and then compare the e-mail addresses as a string.
js code:
function OnEvent_ChatWndReceiveMessage (pChatWnd, sOrigin, sMessage, nMessageKind) {
// Don't do anything when this is not a one-to-one chat.
if ( pChatWnd.Contacts.Count !== 1 ) return sMessage;
// Get the e-mail address to look for.
var sEmail = new Enumerator(pChatWnd.Contacts).item().Email;
// Loop through the e-mails array and look for this e-mail.
var i = oEmails.length;
while ( i-- ) {
if ( sEmail === oEmails[i] ) {
return '';
}
}
}
For more information about array loops and performance in JavaScript/JScript, have a look at this article on Ajaxian.
quote:
Originally posted by Barathrum
Now it works, but it sets messege for all to ' ' instead for only the email I set.
Hmm, that's pretty odd. Could you try the code snippets above and see if those do any better? (I don't have time to test these myself at the moment.)