简体   繁体   English

省略for循环中的第一个参数

[英]Omit first parameter in for loop

In PHP, Java, C++ (and many other languages), for loops are used like this: 在PHP,Java,C ++(以及许多其他语言)中,for循环使用如下:

for(int i=0;i<10;i++)

If I already initialized i , how can I omit the initialization statement? 如果我已经初始化了i ,我怎么能省略初始化语句?

In Java, C++ and PHP it is completely valid to omit the initialization portion of the for loop 在Java,C ++和PHP中,省略for循环的初始化部分是完全有效的

int i = 0;
...
for(; i < 10; i++);

This is true of most languages which have a for loop structure 大多数具有for循环结构的语言都是如此

for(; i < 10; i++) {
    ...
}

You can leave out any of the items in the for loop if they are not needed. 如果不需要,您可以省略for循环中的任何项目。 You could also put in multiple things to do, or multiple conditions to check such as: 您还可以放置多个要做的事情,或者检查多个条件,例如:

int j = 40;
for(int i = 0; i < 10 || j > 30; i++, j--) {}

I think for C++, PHP you could just do this. 我认为对于C ++,PHP你可以这样做。 Not sure of the syntax for other languages. 不确定其他语言的语法。 You could do the same with a while statement if you want to declare outside the loop. 如果要在循环外声明,可以使用while语句执行相同操作。

for(;i<10;i++)

不要忘记,如果你有一个迭代的数组并且不想使用标准的“for”,你总是可以使用“foreach($ array as $ var)”(在PHP上)或其他“for”( X:)“在Java上:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM