当我尝试为数组的特定索引分配值时,它会显示错误。
PS /home/mifi> $names = @()
PS /home/mifi> $names[1]="abc"
Index was outside the bounds of the array.
At line:1 char:1
+ $names[1]="abc"
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], IndexOutOfRangeException
+ FullyQualifiedErrorId : System.IndexOutOfRangeException
pwsh -v
PowerShell v6.0.2
`
答案 0 :(得分:1)
那是因为你必须首先初始化数组。如果您知道数组的大小,可以这样做:
$arraySize = 10
$names= 1..$arraySize | foreach { $null }
考虑使用哈希表:
$names = @{}
$names[1] = "abc"