开发者

How do I declare multiple vars in JavaScript's "for" statement?

for(var i = 0, var p = ''; i < 5; i++)
{
    p +开发者_StackOverflow社区= i;
}

Based on a JavaScript book i'm reading, this is valid code. When I test it doesn't work, and in FireBug I get this error:

SyntaxError: missing variable name


var i = 0, var p = '';

should be

var i = 0, p = '';

the var keyword applies to the whole line.


It looks like a typo.

You need to remove the second var and it will work perfectly:

for(var i = 0, p = ''; i < 5; i++)
{
    p += i;
}


var p = 0;
var i = 0;


for(i = 0; i < 5; i++)
{
    p += i;
}

or

for(var i = 0, p = 0; i < 5; i++)
{
    p += i;
}


remove the var from before p = ''.


Don't repeat the var, you only need it once in the declaration:

for (var i = 0, p = ''; i < 5; i++)
{
    p += i;
}


you can't declare a variable in the second position termitation expression is the following works

var p;
for(var i = 0, p = ''; i < 5; i++)
{
    p += i;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜