简体   繁体   中英

Javascript: refactor function outside of loop

So JSHint tells me I should not make functions within a loop. I then usually make a function outside the loop.

But now I have a part where this is more difficult:

for (r=0;r<x;r++) {
    for (c=0;c<y;c++) {
        var arr = [c,r];
        setTimeout( (function(arr) { return function() { doSomething(arr); };})(arr), 50+c*550 + r*230 );
    }
}

how could i refactor this part to not get the JSHint warning?

It is simple:

for (r=0;r<x;r++) {
    for (c=0;c<y;c++) {
        var arr = [c,r];
        setTimeout( proxy(arr), 50+c*550 + r*230 ); 
    }
}

function proxy(arr){
    return function(){
        doSomething(arr);
    };
}

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