javascriptparametersfor-loopreturn

javascript for loop "jump over value"


hi guys I have a small piece of code in jquery and I have a problem. It seems that for loop jumps over the second parameter ( when i = 2), can you tell me what's wrong?

here is code:

    var items = $(".item").length;
    var currentIndex = items;

    place(currentIndex);

    function place(index){
        var s1 = Math.floor(items / 2);

        for (i = 1; i <= items; i++){
            (function(i, index){

                if (i <= s1){
                    var id = findNext(1, i);
                    console.log("i = " + i + " > id = " + id);
                } else if ( i > s1){
                    console.log("i = " + i);
                }

            })(i, index);
        }
    }

    function findNext(index, times){
        var result = index;

        for (i = 1; i <= times; i++){
            if (result == items){
                result = 1;
            } else {
                result ++;
            }
        }

        return result;
    }

console output shows this :

i = 1 > id = 2
i = 3
i = 4

so it seems that for loop jumps over the second parameter (when i = 2) can you tell me what's wrong?


Solution

  • In your primary loop inside the function place, you define a global variable i. You do the same inside findNext thus overwriting the original i variable. Define i using the var keyword so it is only accessible inside the scope in which it was created.

    for (var i = 0; i <= items; i++) {