2

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

6
  • I presume "livingroomTableData" is an array? Commented May 31, 2012 at 7:59
  • 1
    You have livingroomTableData then livingroomTableArray - are these different objects? Commented May 31, 2012 at 8:03
  • You’ve actually already achieved what you want in terms of data being local to the function. What console error are you getting? Note that, with your for loop conditions, unless data[0] is a number, i++ will cause an error after the code in the for loop runs for the first time. Commented May 31, 2012 at 8:03
  • 1
    +1 for being new and still knowing not to polute the global scope. Commented May 31, 2012 at 8:21
  • @verimilitude Yes it is an array Commented May 31, 2012 at 9:23

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

@PaulD.Waite Please read his code, he is simply wrapped the code in a function, which won't work.
@xdazz: sure — with the code as he provided, his for loop won’t ever run.
1

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.