arrays - 试图理解循环
问题描述
来自 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。
解决方案
翻译是
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++
推荐阅读
- python - Selenium Python - 无法通过 Xpath 选择
- c# - 如何使用 CefSharp 在 winforms 中授权代理(登录名:密码:ip:端口:连接类型)?
- c# - NET5 JWT 不记名身份验证不识别 SSL 证书
- github-pages - 从 haproxy 转发到 github 页面:获取重定向而不是反向代理直通
- asp.net-mvc - 使页面响应并失去对输入字段的关注
- powershell - 从服务器中提取打印驱动程序并使用 Powershell 将它们安装到工作站
- unity3d - 如何在统一单击按钮时不触发 getMouseButtonDown(0)?
- typescript - 使用 Apollo 在 TypeScript 中填充常量时,对象的类型为“未知”.Vetur(2571)
- java - 为什么java找不到我的json文件?我检查了拼写和一切
- python - 在 Python 的不同级别上显示同一行代码