2

我是一个自学成才的新手程序员,我觉得这是一个非常基本的问题,如果我真的学过计算机科学,我就能回答这个问题:P 在我搜索 intertrons 和 StackOverflow 时,我没有无法找到我正在寻找的答案。所以我希望有人可以放纵我。

我有一个对象集合。我想一次对它们进行五个操作,然后继续进行下一个五个。上下文是重启一堆虚拟机;我被要求错开它们,这样主机就不会因为所有虚拟机同时重新启动而受到猛烈抨击。

我觉得正确的道路是for i某种能力的循环,而不是foreach. 我也觉得它可能是和的组合,do-untilfor 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

谢谢大卫!

4

1 回答 1

2

你没有说你的对象在什么样的容器中。我假设它是一个数组。所以,你可以这样做:

for($i=0; $i -lt $objectArray.length; $i+=5)
{
    #do something with $objectArray[$i]
}
于 2012-06-13T16:34:50.313 回答