首页 > 解决方案 > 试图理解循环

问题描述

来自 Python 的 Powershell 脚本的新手。我只是不确定为什么 '$i += 1' 没有在第一个 'write-host("i: ")' 之前覆盖 $i :

$myList = 5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123

write-host("using for loop")
for ($i = 0; $i -le ($myList.length - 1); $i += 1){
    write-host("i: ")
    $i
    write-host("myList[i]: ")
    $myList[$i]
}

我不明白分号在做什么以及它与下面的代码块有何关系。代码按我的意愿工作。但我将其读作“如果 i 小于或等于 9,则将 i 初始化为 0-将 i 增加 1”。但如果是这种情况,那么 i 将在第一次执行 write-host 之前设置为 1。相反,它传递 0 然后递增 $i。

标签: arrayspowershellloopsfor-loop

解决方案


翻译是

set $variable equal to 0; do a thing while $variable is less than OR equal to (<number of items in list> -1);finally set $variable equal to $variable + 1

for (<Initial iterator value>; <Condition>; <Code to increase iterator>)
{
    <Statement list>
}

Statement list执行之前_Code to increase iterator

步骤1

在 for 循环语句的开头,初始值被读取并存储到内存中。

例子:$i = 0

第2步

for 循环语句计算 Condition 占位符内表达式的布尔结果。如果结果为 $false,则终止 for 循环。如果结果为 $true,则 for 循环继续执行下一步。

例子:$i -le ($list.length -1)

第 3 步

PowerShell 在语句列表占位符内运行代码。可能有一个或多个命令、脚本块或函数。

例子:Write-Ouput $i

第4步

在这一步中,Repeat 占位符中的表达式运行,它将更新 Initial placeholder 的当前值。然后,流程将返回到第 2 步。

例子:$i++


推荐阅读