javascript scope problem with 'global' arrays
I know, I know, don't use global variables. But I've used them for all sorts of control structures over the years and they work fine for this old-time modular 'I object to objects' guy.
My current issue has to do with 'disappearing scope' of arrays that are declared global, filled out later and then referenced from elsewhere. I often do the following on my main html page:
<...>
<script type="text/javascript" src="./js/arrayStuff.js"></script>
<script type="text/javascript" src="./js/printStuff.js"></script>
<script type="text/javascript>
var gGlobalArray = new Array();
loadgGlobalArray();
printgGlobalArray();
</script>
</head>
<html>blah blah
</html>
Then I'll have something like this in the arrayStuff.js file to make a multidimensional array whose size isn't known in advance:
function loadgGlobalArray()
{
<...>
gGlobalArray[rawFileIndex] = new Array(9);
gGlobalArray[rawFileIndex][0] = currentPathIndex;
gGlobalArray[rawFileIndex][1] = currentCtlName;
gGlobalArray[rawFileIndex][2] = currentStepbounds;
<...>
In the file printStuff,js, I can reference the different dimensions OK:
<...>
buffer += "<td>"+gGlobalArray[i][7]+</td><td>+gGlobalArray[i][8]+</td>";
document.getElementByID('output').innerHTML = buffer;
<...>
Now I'm working on a new .js external file, and here's what's got me stumped. Sometimes my old-school global arrays work as I intend them and sometimes they don't. I know Javascript arrays are really 开发者_StackOverflow中文版objects, and can sort of understand why the length property might not be available, for example, but the kicker is that my arrays behave as intended as long as I leave my usual debugging alerts in the external files. If I comment out all the alerts, the internal array information disappears, length property goes away, etc. If I put a single alert statement in the bit where I'm filling out the array, even if the alert doesn't refer to the array itself, the information is preserved. Why?
There's nor reason the length shouldn't be available, assuming you really defined the array as you did. Maybe something else is happening, such as you refer to it in a file before the other file is loaded, or something. The alert might be causing a pause that lets the stuff load.
BTW, you should look into object and array literal notation:
gGlobalArray[rawFileIndex] = new Array(9);
gGlobalArray[rawFileIndex][0] = currentPathIndex;
gGlobalArray[rawFileIndex][1] = currentCtlName;
gGlobalArray[rawFileIndex][2] = currentStepbounds;
could be
gGlobalArray[rawFileIndex] = [
currentPathIndex, currentCtlName, currentStepbounds...];
Much shorter and easier to look at.
精彩评论