Thursday, January 13, 2011

Firefox and undefined array elements

So here's a Javascript question. Now I admit I'm not a Javascript expert so this ones got me a bit stumped.


In the following code snippet I'm trying to get a function to do something only when it is
first called. It can be called with a number of items (identified by an integer I), it
should call itself only the first time it is called with that arguement. I have an array (lsaCall)
with only the first item defined (and set to 0). If the array element is undefined (or 0) then the function
calls itsel on a timer.

var lsaCall = [0];
function loadSubscribedArticles(i,tag,Author){
 
 //alert("lsaCall "+lsaCall[i]);
 if ((lsaCall[i]==undefined) || (lsaCall[i] ==0)) {
  lsaCall[i]=1;
  //alert("Undefined"+lsaCall[i]);
  var int=self.setInterval("loadSubscribedArticles('"+i+"','"+tag+"','"+Author+"')",1000);
  
 }
}

This works fine and dandy but doesn't work at all in firefox. It complains that lsaCall
is undefined (well I know that !)
Any ideas on how to get this working in firefox ? Is there a better way of doing it ?

1 comment:

  1. Hey Andy,

    I think Firefox is just having a problem with the 'undefined' check. I've rewritten the function to use stricter checking. The typeof operator returns the type of an object as a string, and all browsers are happy with its usage. I've also turned your == equality checker to ===. == and != use JavaScript type casting to check for truthys and falsies across types, but using === and !== enforces the type.

    Here's the updated code: https://gist.github.com/777690

    I also moved your int declaration to the top of the function because that's what JavaScript does at runtime. By forcing yourself to declare all vars at the top of a function, you can avoid a lot of head scratching later on!

    ReplyDelete