views:

168

answers:

3

Hey guys, I am trying to add the returned value from the test() function into a the 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 ofc).

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);

     }
+5  A: 

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);
}
GMan
the result is a string, it should be initialized to '' not 0.
Brian Schroth
Just fixed that. :)
GMan
Thanks HEAPS!! This solved the whole thing!
meow
No problem, welcome to StackOverflow.
GMan
A: 

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

Peter
A: 

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.

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