我目前正在尝试创建一个程序来训练外语。
为此,我有两个一维数组。在第一个中,我存储所有外来音节或单词,而在第二个中,我以母语存储答案:
$QuestionArray = New-Object System.Collections.ArrayList
$QuestionArray = "Word1","Word2","Word3"
$AnswerArray = New-Object System.Collections.ArrayList
$AnswerArray = "Answer1","Answer2","Answer3"
之后,我检查输入的值是否在答案数组内。如果是,则从问题数组中选择索引和随机选择的单词的索引。如果两个索引都匹配,则问题已被回答正确,否则错误。
$RandomQuestion = $QuestionArray | Get-Random
$Answer = $InputTextbox.Text
$IndexPositionQuestion = [array]::indexof($QuestionArray, $RandomQuestion)
$IndexPositionAnswer = [array]::indexof($AnswerArray, $Answer)
If($IndexPositionAnswer -eq $IndexPositionQuestion){
$RightTextbox.Text = $script:countercorrect++
}else{
$WrongTextbox.Text = $script:counterwrong++
}
该程序按预期工作,但是当我今天向同事展示时,他只是告诉我,该程序的比较部分编码丑陋,绝非最佳实践。
我该如何以其他方式处理?我读了一些关于多维数组的内容,但是我无法解决这个问题。我如何从多维数组中受益?我如何从中选择显示,比较,检查等所需的值?
最佳答案
在研究多维数组之前,为什么不尝试使用带有哈希表的数组呢?
$array = @(
@{
Question = 'blah?'
Answer = 'blub'
},
@{
Question = 'james'
Answer = 'Dean'
}
)
您可以通过以下方式引用值
for($i = 0; $i -lt $array.Count; $i++){
$array[$i].Question
$array[$i].Answer
}
在你的例子中尝试类似
$RandomQuestionNr = 0..($QuestionArray.count -1) | Get-Random
$Answer = $InputTextbox.Text
if($array[$RandomQuestionNr].answer -eq $Answer){
$RightTextbox.Text = $script:countercorrect++
}else{
$WrongTextbox.Text = $script:counterwrong++
}
关于arrays - 多维数组如何在PowerShell中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41485677/