Jslint - don't execute functions inside a loop

Referring to this topic: Do not perform functions inside a loop. - jslint error

How would you handle jquery.each (function () {...} in a for loop?), Knowing that I need a "for" context in my "every" function. Of course, I could match all the parameters for a function - a function declared outside the loop, but from my point of view it affects readability.

Any thoughts?

Thanks in advance.

+5
source share
3 answers

Well, you can keep the for context in your loop, because everything in this case is actually in the same context as the function declared at the beginning.

, , JSLint ( , ).

/*global console*/
var my_func, i, list;
for (i = 0; i < list.length; i+= 1) {
    my_func = function (i) {
        console.log(i);
    };
    my_func(i);
}

, , , my_func. ! ?

, :

/*global console*/
var my_func, i, list;

my_func = function (i) {
    console.log(i);
};

for (i = 0; i < list.length; i+= 1) {
    my_func(i);
}

. . , JSLint , var , .


: @Flame , jQuery each , , each. , 1.) 2.) jQuery (, index), JSLint ( ) , each (jQuery sauce ).

, $.each(function() {});, .

/*global alert, $ */
$( "li" ).each(function( index ) {
    alert( index + ": " + $(this).text() );
});

... ...

/*global $, alert */
var fnOutside = function(index) {
    alert( index + ": " + $(this).text() );
};
$( "li" ).each(fnOutside);

, , jQuery - , "index" . arguments, , , .

Fiddle-ige

for . . !

+9

: this,

for (var i = 0; i < list.length; i+= 1) {
    function my_func(i) {
        console.log(i);
    }
    my_func(i);
}

:

var my_func;
for (var i = 0; i < list.length; i+= 1) {
    my_func = function (i) {
        console.log(i);
    }
    my_func(i);
}

- . (.. ). for.

for, .

, :

$("..").each(function () {
    for(..) {
    }
});

.

for(..) {
    $("..").each(function () {

    });
}

, :

var my_func;
for(..) {
    my_func = function () {
        // ..
    }
    $("..").each(my_func);
}
+4

, , . , JSLint , .

Q & A : JSLint JSHint JavaScript? lint , JSLint, , Crockford.

, JavaScript .

+2

All Articles