我是一名自学成才的新手程序员,我觉得这是一个非常基本的问题,如果我真的学过计算机科学,我就能回答这个问题:P在我搜索intertrons和StackOverflow我一直无法找到我正在寻找的答案。所以我希望有人可以放纵我。
我有一组对象。我想一次操作五个,然后继续下一个五个。上下文正在重启一堆虚拟机;我被要求错开它们,这样主机就不会被所有虚拟机重新启动了。
我感觉正确的路径是某个容量的for i
循环,而不是foreach
。我也觉得它可能是do-until
和for i
的组合,但我不能从我的大脑中筛选答案。
我可以通过从集合中删除对象来实现,但这感觉就像“错误”的方式,即使它可以工作。
我正在使用Powershell和PowerCLI这样做,但我觉得我试图理解的逻辑比依赖任何语言更基本,所以即使你不熟悉Powershell,我也是对你的答案感兴趣。
编辑:根据David的回答,以下代码似乎是我正在寻找的:
$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
谢谢大卫!
答案 0 :(得分:2)
你没有说明你的物品是什么类型的容器。我会假设它是一个数组。所以,你可以这样做:
for($i=0; $i -lt $objectArray.length; $i+=5)
{
#do something with $objectArray[$i]
}