arrays - 多维数组如何在PowerShell中工作?

标签 arrays powershell multidimensional-array

我目前正在尝试创建一个程序来训练外语。
为此,我有两个一维数组。在第一个中,我存储所有外来音节或单词,而在第二个中,我以母语存储答案:

$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/

相关文章:

linux - 如何使用 powershell 将 IP 地址解析为 Linux 主机名

javascript - 使用 "file_put_contents"创建和编辑文件 javascript ?

.net - 在 IT 管理之外应用 powershell

c - 解释为什么这两个多维数组看起来是有效的语法,但只有一个给出了预期的结果?

java - java中字符串数组数组的数据结构

c - 数组中的高低值打印在其间

c# - 尽管 list<T> 在内部使用数组(固定的),但它如何动态工作?

C - 基于用户输入的多维数组内存分配

arrays - 在 Ruby 中构建多维数组

node.js - 无服务器框架 sls 与 Powershell sls 冲突(选择字符串)