【问题标题】:use existing variable in for loop在 for 循环中使用现有变量
【发布时间】:2012-05-29 14:14:31
【问题描述】:

是否可以从 for 循环中省略变量赋值并执行类似的操作...?

otherVar = 3;

for ( otherVar > 0; otherVar-- )
{
    stuff
}

【问题讨论】:

  • 你也可以在循环中声明一堆变量:for(var someVar=0, otherVar=3, yetAnother='bob';yetAnother!==false;someVar++)

标签: javascript loops for-loop


【解决方案1】:

是的,但您需要输入分号:

var otherVar = 3;

for ( ; otherVar > 0; otherVar-- ) {
    doStuff();
}

【讨论】:

    【解决方案2】:

    通常虽然在这种情况下更受欢迎(更好的可读性)..

    otherVar = 3;
    
    while ( otherVar > 0)
    {
       stuff
       otherVar--;
    }
    

    【讨论】:

    • 啊,决定按照你的方式去做。不知道为什么我要尝试使用 for 循环。 :)
    • 乐于助人:)。 while 条件的简写是 while( otherVar-- > 0 ) 以防 if 不喜欢在循环结束时使用增量。顺便说一句,+1 是提到答案在 SO 中很有用的好方法。谢谢
    【解决方案3】:

    您可以从任意数字开始倒计时:

    var counter = 3;
    while ( counter-- ) {
      console.log( counter );
    }
    

    哪些输出:2、1、0

    【讨论】:

    • 只是一个简单的问题。如果我错了,请纠正我,但 while 循环一直运行到括号内的表达式正确为止。什么时候 counter-- 变为 false 或 true。
    猜你喜欢
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 2015-11-25
    • 2020-04-05
    • 2019-09-27
    相关资源
    最近更新 更多