开发者

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

开发者 https://www.devze.com 2022-12-15 12:50 出处:网络
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 e
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

精彩评论

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