1

I am trying to add the returned value from the test() function into a variable result, but += does not seem to work. I get the error "invalid variable initialization". I also tried replacing i++ to i+= which didnt work either. Maybe I'm totally wrong and should use a while loop instead? I'm quite lost..

I want 'result' to look something like this:

var result = no no no 0no 0no no;

etc (with no whitespace, of course).

Any help much appreciated! Thanks

function test(no){

            if (no <= 15){              
                return '0' + parseInt(no);
            }

            else {              
                return parseInt(no); 
            }       
}


        for(i = 0; i < pics.length; i++){

            var b = pics[i].value;

            var result += test(b);

        }
2
  • Given the syntax and variable names, I'm assuming JavaScript and have retagged as such. ActionScript (or any other ECMAScript-based language) is another likely choice, but they have identical syntaxes in this example. Commented Nov 18, 2009 at 19:29
  • sorry should have taged it as javascript, my bad Commented Nov 18, 2009 at 19:33

3 Answers 3

5

Every time your loop starts, var result goes away. You need to move it outside the loop:

var result = ''; // lives outside loop
for(i = 0; i < pics.length; i++)
{
    var b = pics[i].value;
    result += test(b);
}
Sign up to request clarification or add additional context in comments.

1 Comment

the result is a string, it should be initialized to '' not 0.
0

you need to initialize result as a string not as a var.

e.g.

outside the loop

string result = string.Empty;

for loop

result += test(b);

end for loop

Comments

0

You are seeing that error because you are using the increment operator on a newly declared variable. Use '=':

for(i = 0; i < pics.length; i++)
{
   var b = pics[i].value;
   var result = test(b);
}

Although, as GMain pointed out, the real solution is to move the 'result' variable declaration outside of the for loop.

4 Comments

result is a cumulative concatenation of the results of test() on each element.
No need for the downvote. I explained the reason for his compile error.
Although you're right about why the interpreter is complaining, so I'll vote you up to zero.
oops - lol... I should remember that C# isn't the only language in existence! Thanks for the upvote...

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.