我是一个自学成才的新手程序员,我觉得这是一个非常基本的问题,如果我真正学习了计算机科学,我就能回答这个问题:P 在我对 intertrons 和 StackOverflow 的搜索中我一直无法找到我正在寻找的答案。所以我希望有人可以包容我。
我有一个对象集合。我想一次对五个进行手术,然后再进行接下来的五个手术。上下文正在重新启动一堆虚拟机;我被要求将它们错开,这样主机就不会因为所有虚拟机同时重新启动而受到冲击。
我感觉正确的路径是某种能力的 for i
循环,而不是 foreach
。我还觉得它可能是 do-until
和 for i
的组合,但我无法从我的大脑中筛选出答案。
我可能可以通过从集合中删除对象来做到这一点,但这感觉像是“错误”的方法,即使它可行。
我正在使用 Powershell 和 PowerCLI 执行此操作,但我觉得我试图理解的逻辑比依赖于任何语言更为基本,因此即使您不熟悉 Powershell,我也可以对你的答案感兴趣。
编辑:根据下面大卫的回答,以下代码似乎是我正在寻找的:
$someLetters = @("a","b","c","d","e","f","g","h","i","j","k")
for($i=0; $i -lt $someLetters.length; $i+=5)
{
Write-Host ("the letter is " + $someLetters[$i] + " and i is " + $i)
Write-Host ("the letter is " + $someLetters[$i+1] + " and i is " + $i)
Write-Host ("the letter is " + $someLetters[$i+2] + " and i is " + $i)
Write-Host ("the letter is " + $someLetters[$i+3] + " and i is " + $i)
Write-Host ("the letter is " + $someLetters[$i+4] + " and i is " + $i)
write-host "finished block of five"
}
给出输出:
the letter is a and i is 0
the letter is b and i is 0
the letter is c and i is 0
the letter is d and i is 0
the letter is e and i is 0
finished block of five
the letter is f and i is 5
the letter is g and i is 5
the letter is h and i is 5
the letter is i and i is 5
the letter is j and i is 5
finished block of five
the letter is k and i is 10
the letter is and i is 10
the letter is and i is 10
the letter is and i is 10
the letter is and i is 10
finished block of five
谢谢大卫!
最佳答案
您没有说您的对象位于哪种容器中。我假设它是一个数组。所以,你可以这样做:
for($i=0; $i -lt $objectArray.length; $i+=5)
{
#do something with $objectArray[$i]
}
关于loops - 一次循环遍历 n 个对象的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11019075/