For Loop仅循环一次js

时间:2016-08-24 16:27:15

标签: javascript variables for-loop var

我是JavaScript的初学者。我试着通过编写更少的代码来使我的工作更轻松,所以我编写了这个..

for (counta = 0; counta < 22; counta++)
{
    window["varEnemyType1" + counta] = document.getElementById("EnemyType1" + counta).options[document.getElementById("EnemyType1" + counta).selectedIndex].text;
    window["varEnemyType2" + counta] = document.getElementById("EnemyType2" + counta).options[document.getElementById("EnemyType2" + counta).selectedIndex].text;
}

在此之前我设置了全球变量,例如(var varEnemyType11 = "";) 我和#count;&#39;&#39;然后分配一个值。

在我的问题排查中,我发现for循环只计算&#39; 0&#39;甚至在功能的其余部分之后也没有任何东西。那是为什么?

2 个答案:

答案 0 :(得分:0)

您需要在counta声明中使用var,例如:

   for ( var counta = 0; counta < 22; counta++ ){
       //your code......
   }

此致

答案 1 :(得分:-2)

你的循环是&#34;确定&#34;,但是你需要捕捉异常来判断它是不是为什么没有超越第一个:

for ( var counta = 0; counta < 22; counta++ )
{
    try
    {
        window["varEnemyType1" + counta] = document.getElementById("EnemyType1" + counta).options[document.getElementById("EnemyType1" + counta).selectedIndex].text;
        window["varEnemyType2" + counta] = document.getElementById("EnemyType2" + counta).options[document.getElementById("EnemyType2" + counta).selectedIndex].text;
    }
    catch (ex)
    {
        //You should be doing this, but you might not know how to get to the console
        console.log( ex );

        alert( ex );
    }
}