简体   繁体   中英

Global variable not updating outside function

Trying to make variable created inside function possible to access globally, so far

console.log(proper_head);

constantly displays "1" while I need it to be updated every time the function is executed, here is my function:

var i = 0;
function change_head() {
    if (i < head_class.length) {
        head.classList.add(head_class[i].name);
        i++;
        var h = i;
        return h;
    } else if (i = 3) {
        head.className = "";
        i -= 3;
        var h = i;
        return h;
    }
}
var proper_head = change_head();

it is executed by pressing a button (not sure if it's important). The only solution I came up with is to

 setTimeout()

I'm sure there is a better way.

You could use a recursive implementation like this:

var i = 0;
function change_head() {
    if (i < head_class.length) {
        head.classList.add(head_class[i].name);
        i++;
        var h = i;
        return h;
    } else if (i = 3) {
        head.className = "";
        i -= 3;
        var h = i;
        return h;
    }
change_head();
}

The problem is that your function is only being called once, you can call the function from within itself, however the above example will never stop, and will probably hit the max call stack size in your browser and then crash, i would recommend wrapping it in some sort of if statement so that it stops at some point, eg i > 50.

Edit:

I see what your actual problem is, neither of your if blocks are firing, after the first press, head_class.length === 1 so "if (i < head_class.length)" wont fire, it's also not equal to 3 for the else block so nothing happens, the else block also has an error, try changing it to this:

if (i < 3) {
        head.classList.add(head_class[i].name);
        i++;
        var h = i;
        return h;
    } else if (i == 3) {
        head.className = "";
        i -= 3;
        var h = i;
        return h;
    }

i = 3 is for assignment, i == 3 is for comparison.

Hope this helps

Lloyd

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