日期:2014-05-16  浏览次数:20458 次

JS 中全局变量和局部变量的问题
可能是因为全局变量和局部变量定义问题,总是出错.
我的代码如下:
<html   xmlns= "http://www.w3.org/1999/xhtml ">
    <head>
        <meta   http-equiv= "content-type "   content= "text/html;   charset=utf-8 "/>
        <title> Glider   WPT </title>

        <script   type= "text/javascript ">
var   LGMN   =   -6;
var   LGMX   =   37;
var   LTMN   =   30;
var   LTMX   =   50;
var   ltn   =   new   Array();
var   ltx   =   new   Array();
var   lgn   =   new   Array();
var   lgx   =   new   Array();
var   latDelta   =   5;
var   lngDelta   =   6;
var   n   =   0;
var   m   =   0;
function   load(){
for(var   i=LTMN;   i <LTMX;   i=i+latDelta){
ltn[n]   =   i;
ltx[n]   =   i+latDelta;

for(var   j=LGMN;   j <=LGMX;   j=j+lngDelta){
lgn[m]   =   j;
lgx[m]   =   j+lngDelta;
m++;
}
n++;
}
alert(ltn.length);   //------>   4   ????????????????????????
}

function   affichager(){
document.write(ltn.length);   //-------> 0   ???????????????????????
}
</script>

    </head>
    <body   onload= "load() "   onunload= "GUnload() ">
<?php
$k   =   ' <script   type= "text/javascript ">   affichager()   </script> ';
echo   $k;
?>

    </body>
</html>

为什么两次输出的ltn.length(问号处)结果不一样呢?   怎样解决这个问题?
希望高手解答.

------解决方案--------------------
试试这个你就明白了:

<html xmlns= "http://www.w3.org/1999/xhtml ">
<head>
<meta http-equiv= "content-type " content= "text/html; charset=utf-8 "/>
<title> Glider WPT </title>

<script type= "text/javascript ">
var LGMN = -6;
var LGMX = 37;
var LTMN = 30;
var LTMX = 50;
var ltn = new Array();
var ltx = new Array();
var lgn = new Array();
var lgx = new Array();
var latDelta = 5;
var lngDelta = 6;
var n = 0;
var m = 0;
function load(){
for(var i=LTMN; i <LTMX; i=i+latDelta){
ltn[n] = i;
ltx[n] = i+latDelta;

for(var j=LGMN; j <=LGMX; j=j+lngDelta){
lgn[m] = j;
lgx[m] = j+lngDelta;
m++;
}
n++;
}
alert( "后赋值! "+ltn.length); //------> 4 ????????????????????????
}

function affichager(){
alert( "这里先执行! ");
document.write(ltn.length); //-------> 0 ???????????????????????
}
</script>

</head>
<body onload= "load() " onunload= "GUnload() ">
<?php
$k = ' <script type= "text/javascript "> affichager() </script> ';
echo $k;
?>

</body>
</html>
------解决方案--------------------
window.onload=function(){load();affichager();}
两个都放在o