gpt4 book ai didi

loops - 一次遍历对象的集合n

转载 作者:行者123 更新时间:2023-12-02 23:48:07 25 4
gpt4 key购买 nike

我是一个自学成才的新手程序员,我觉得这是一个非常基本的问题,如果我真的学习过计算机科学,那么我将能够回答该问题:P在搜索intertrons和StackOverflow时,我还没有'找不到我要找的答案。所以我希望有人可以放纵我。

我有一些 object 。我想一次对它们进行五个操作,然后继续进行下五个操作。上下文正在重新引导一堆VM。我被要求将它们错开,以免主机被立即重新引导的所有VM所撞击。

我感觉到正确的路径在某种程度上是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

谢谢大卫!

最佳答案

您没有说对象在哪种容器中。我假设它是一个数组。因此,您可以执行以下操作:

for($i=0; $i -lt $objectArray.length; $i+=5)
{
#do something with $objectArray[$i]
}

关于loops - 一次遍历对象的集合n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11019075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com