简体   繁体   中英

can global variables be incremented in javascript

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);
}

My question is that after the p increments that is p++ will my var p = 1 be incremented everytime I call doMove ? Please help me regarding this matter.

By definition global variables have global scope, so you can increment them or re-assign them within a function and that will work, how fantastic is that!

Although as Borgtex has pointed out your if statement won't work

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

You have declared the variable t in another function so your doMove() function does not have access to it, therefore this statement will always return false ; If you make t a global variable or pass it into your doMove() function as a parameter then this will work.

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"); 
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM