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);
}
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);
}
Share
Improve this question
edited Feb 15, 2012 at 14:35
Chris Barlow
3,3144 gold badges34 silver badges52 bronze badges
asked Nov 18, 2009 at 19:23
patadpatad
9,69211 gold badges42 silver badges44 bronze badges
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. – Cory Petosky Commented Nov 18, 2009 at 19:29
- sorry should have taged it as javascript, my bad – patad Commented Nov 18, 2009 at 19:33
3 Answers
Reset to default 5Every 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);
}
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
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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745139516a4613363.html
评论列表(0条)