Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutable variable is accessible from closure [duplicate]

I have the following code:

for (var i = 0; i < data.length; i++) {
        var file = data[i];
        $.getJSON("/types/" + file, function(json) {
            if (json[0] !== undefined) {
                console.log(json[0] + file);
            }
        });
    }

But my editor is saying "Mutable variable is accessible from closure". I've tried to change function(json) { to function(json, file) {, but this don't work because this is a default function of jquery.

I hope you can help my fixing the problem.

like image 204
jan Avatar asked Nov 28 '22 04:11

jan


1 Answers

For such loops, you need to put the contents in a closure.

for (var i = 0; i < data.length; i++) {
    (function(){
        var file = data[i];
        $.getJSON("/types/" + file, function(json) {
            if (json[0] !== undefined) {
                console.log(json[0] + file);
            }
        });
    })();
}
like image 73
Van Coding Avatar answered Dec 09 '22 19:12

Van Coding