search

Home  >  Q&A  >  body text

Is var elem a global variable or a local variable, especially when declared within a function object?

function styleHeaderSiblings() {
    if(!document.getElementsByTagName) return false;
    var headers = document.getElementsByTagName("h1");
    var elem;
    for(var i=0; i<headers.length; i++) {
        elem = getNextElement(headers[i].nextSibling);

        elem.style.fontWeight = "bold";
        elem.style.fontSize = "1.2em";
    }
}
PHP中文网PHP中文网2836 days ago472

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-05-19 10:29:05

    Just take you for语句里面的var i = 0来说,变量i在函数体内都能访问到,而不仅局限于for inside the loop.

    Variables declared with var are within the function scope.

    If you want to declare block-level variables, use const或者let.

    reply
    0
  • ringa_lee

    ringa_lee2017-05-19 10:29:05

    It is a local variable inside the function and cannot be accessed outside the function.

    reply
    0
  • Cancelreply