可以通过闭包访问可变变量 [英] Mutable variable is accessible from closure

查看:97
本文介绍了可以通过闭包访问可变变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

但是我的编辑说可以从闭包中访问Mutable变量。我试图将函数(json){更改为函数(json,file){,但这不要这是因为这是jquery的默认函数。

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.

推荐答案

对于此类循环,您需要将内容放入闭包中。

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

这篇关于可以通过闭包访问可变变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆