Sony packman
Sony packman

Reputation: 840

For loop inside function (newbie)

I would like to have some variables that my for loop uses inside a function scope (not global).

I tried to wrap the for loop inside a function like this but it results in console error:

function() {
    var data = livingroomTableData;
    for(var i = data[0]; i < data[1]; i++) {
        var elemvalue = data[2] + format(i) + ".png";
        livingroomTableArray[i] = elemvalue;
    }
}

I would like the data variable to have the values of livingroomTableData only inside this for loop (not globally). In other loops I will input a different variable into the data variable.

Oh yes, and as you can probably tell, I'm a total newbie. :S

Upvotes: 2

Views: 3336

Answers (3)

RichardTowers
RichardTowers

Reputation: 4762

The big problem is this line:

for(var i = data[0]; i < data[1]; i++) {  

That means, starting with i as the first element of the array, do the code in the loop, incrementing i by one at the end of each run until i is not less than the second element of data.

I'd rewrite it to show you a working version, but its not clear what you actually want to do.

Upvotes: 1

Someth Victory
Someth Victory

Reputation: 4549

function() {
    for(var i = 0; i < livingroomTableData.length; i++) {
        var data = livingroomTableData[i];
        //your code here...
    }
}

Upvotes: 0

xdazz
xdazz

Reputation: 160853

There is only function scope in javascript, block scope does not exist, so you can't let the variable only inside the for loop. What you could do is to create a function scope.

Code example:

(function(livingroomTableData) {
    var data = livingroomTableData;
    //... the rest code
})(livingroomTableData);

Upvotes: 1

Related Questions