You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改PowerShell代码实现按步长4遍历数组$a2分组元素

PowerShell数组分组遍历修改方案

你需要根据循环变量动态计算当前分组的起始索引,替代原来固定的4-7索引。修改后的代码如下:

for ($i = 0; $i -lt 10; $i++)
{
    # 计算当前组的起始索引:从第2组开始,每次步进4
    $startIndex = 4 * ($i + 1)
    # 输出当前组的四个元素
    $a2[$startIndex]
    $a2[$startIndex + 1]
    $a2[$startIndex + 2]
    $a2[$startIndex + 3]
}

或者用更简洁的数组切片写法,一次性输出整组:

for ($i = 0; $i -lt 10; $i++)
{
    $startIndex = 4 * ($i + 1)
    $a2[$startIndex..($startIndex + 3)]
}

说明

  • 数组$a2中每组4个元素,第1组索引为0-3,第2组为4-7,以此类推。
  • 循环变量$i从0到9(共10次),通过4 * ($i + 1)计算出第$i+2组的起始索引:
    • 当$i=0时,起始索引为4,对应第2组(id2)
    • 当$i=9时,起始索引为40,对应第11组(id11)
  • 这样每次循环都会自动步进4,遍历后续的分组数据。

内容的提问来源于stack exchange,提问作者evgenij

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 03:02:08