$scores = [ordered]@{
Jack = 81;
Mike = 78;
Mark = 99;
Jim = 64;
}
$grades = [ordered]@{}
$len = $scores.Count
for ($n=0;$n -lt $len; $n ){
if ($($scores.values)[$n] -gt 65){
$grades = @{$($scores.keys)[$n] = $($scores.keys)[$n]}
$grades[$n] = $($scores.values)[$n] = "PASS"
}
else{
$grades = @{$($scores.keys)[$n] = $($scores.keys)[$n]}
$grades[$n] = $($scores.values)[$n] = "FAIL"
}
}
$grades
=======以上在 POWERSHELL 中作業得很好
*******以下是 POWERSHELL 中的問題(此結構在 Python 中有效)
$scores = [ordered]@{
Jack = 81;
Mike = 78;
Mark = 99;
Jim = 64;
}
$grades = [ordered]@{}
foreach($key in $scores){
if ($scores[$key] -gt 65){
$grades[$key] = "PASS"
}
else{
$grades[$key] = "FAIL"
}
}
$grades
======== 這是正確的 FOR 回圈輸出:
******** 以下是 FOREACH 的輸出:
請告訴我 FOREACH 回圈是如何失敗的。
(對 FOR 回圈的任何改進都是錦上添花!)
uj5u.com熱心網友回復:
該foreach示例缺少.Keys(建議使用.PSBase.Keys)或.GetEnumerator()為了列舉它:
$scores = [ordered]@{
Jack = 81
Mike = 78
Mark = 99
Jim = 64
}
# - Using `.PSBase.Keys`
$grades = [ordered]@{}
foreach($key in $scores.PSBase.Keys) {
if ($scores[$key] -gt 65) {
$grades[$key] = "PASS"
continue
}
$grades[$key] = "FAIL"
}
# - Using `.GetEnumerator()`
$grades = [ordered]@{}
foreach($pair in $scores.GetEnumerator()) {
if ($pair.Value -gt 65) {
$grades[$pair.Key] = "PASS"
continue
}
$grades[$pair.Key] = "FAIL"
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/451085.html
