在Javascript中访问全局变量时出现问题

时间:2013-03-06 10:45:53

标签: javascript

我无法在第二个函数中访问NatArray [],第二个函数中的u4count变为0.可能是什么原因?

<script type="text/javascript">

var NatArray = [];
var NatArrayloc = [];
var u4count = 0;

function Check1()
{
NatArray[0] = 202116108;
NatArrayloc[0] = 202116109;
NatArray[1] = 202116111;
NatArrayloc[1] = 202116112;
NatArray[2] = 202116113;
NatArrayloc[2] = 202116114;
u4count = 3;
}
function Check()
{
 alert("coming here" + u4count + "natentry" + NatArray[0] );
}
</script>

先谢谢

3 个答案:

答案 0 :(得分:1)

对我来说是受到怀疑的。在这种情况下,您强调的功能

var NatArray = [];
var NatArrayloc = [];
var u4count = 0;

function Check1() {
    NatArray[0] = 202116108;
    NatArrayloc[0] = 202116109;
    NatArray[1] = 202116111;
    NatArrayloc[1] = 202116112;
    NatArray[2] = 202116113;
    NatArrayloc[2] = 202116114;
    u4count = 3;
}

function Check() {
    alert("coming here " + u4count + " natentry " + NatArray[0]);
}

Check1();
Check();

正如一些回答用户所发现的那样,未公开的内联评论不好,但不是你问题的原因。 Something about comments in inline-code

http://fiddle.jshell.net/r8sKf/

答案 1 :(得分:1)

你可以在window.onload中调用这2个函数,这样它就会调用第二个函数,并在警报内提醒NatArray[ ]值。

尝试这样的事情:

var NatArray = [];
var NatArrayloc = [];
var u4count = 0;

function Check1() {
    NatArray[0] = 202116108;
    NatArrayloc[0] = 202116109;
    NatArray[1] = 202116111;
    NatArrayloc[1] = 202116112;
    NatArray[2] = 202116113;
    NatArrayloc[2] = 202116114;
    u4count = 3;
}

function Check() {
    alert("coming here " + u4count + " natentry " + NatArray[0]);
}

 window.onload=function(){
        Check1();
        Check();
    };

答案 2 :(得分:-2)

你走了:

http://jsfiddle.net/R23eD/

您需要从脚本开始删除<!--。而且你也没有调用Check1()函数初始化值