可以在javascript中增加全局变量

时间:2013-05-24 08:23:58

标签: javascript variables scope increment

var t = 0;
function addDiv()
{
    var div = document.createElement("div");
    t++;
    div.setAttribute("id", "box" + t);
    document.body.appendChild(div);
    AddStyle();
}

var h = 0;
var p = 1;    
function doMove()
{
    var okj = document.getElementById("box" + p);

    if (p <= t) {
        p++; 
    }
    var g = setInterval(function () {
        var go = parseInt(okj.style.left, 0) + 1 + "px";
        okj.style.left = go;
    }, 1000 / 60);
}

我的问题是,在p + p递增后,每次调用var p = 1时我的doMove会递增吗?请帮我解决这个问题。

1 个答案:

答案 0 :(得分:2)

根据定义,全局变量具有全局范围,因此您可以递增它们或在函数内重新分配它们并且这将起作用,这太棒了!

虽然Borgtex指出你的if陈述不起作用

if (p <= t) {
   p++; 
}

您已在另一个函数中声明变量t,因此您的doMove()函数无权访问它,因此此语句将始终返回false;如果您将t设为全局变量或将其作为参数传递给doMove()函数,那么这将有效。

var p = 1; // this variable is global

function varTest(){
   p++ //This will work because p is global so this function has access to it.
   var t = 0;
}

function anotherTest(){
   if(p<t){   //This will return false - t is not in scope as it was defined in another function
      alert("supercalifragilisticexpihalitoscious"); 
   }
}