找出PowerShell
中与其他语言相比有多少有趣的数组。
这是我的开始:
$testArr = (1,2,3),(4,5,6)
这就是我要结束的内容:(1,2,3,0),(4,5,6,0)
我试图得到的是:foreach($x in $testArr) { $x += 0 }
和$testArr | % { $_ += 0 }
但是,当我尝试输出$testArr
时,我得到的开始是:(1,2,3),(4,5,6)
。我发出一个调用以输出循环中正在使用的当前数组,并在添加0
后看到+= 0
在数组中,但是由于某种原因,它不想卡住当我输出二维数组时。我缺少PowerShell
数组的哪个方面?
答案 0 :(得分:2)
For ($i = 0; $i -lt $testArr.Count; $i++) {$testArr[$i] += 0}
重点是数组实际上是固定大小的。
证明:
foreach($x in $testArr) { $x.Add(0) }
使用“ 1”作为参数调用“添加”的异常:“集合的大小固定。”在第1行:char:27
+ foreach($ testArr中的$ x){$ x.Add(0)}
+ ~~~~~~~~~~
+ CategoryInfo:未指定:(:) [],MethodInvocationException
+ FullyQualifiedErrorId:NotSupportedException
换句话说,当您使用+=
赋值运算符时,实际上是在创建数组的副本并将其重新分配给变量。
证明:
PS C:\> $a = 1,2,3
PS C:\> $b = $a
PS C:\> $a += 4
PS C:\> $a
1
2
3
4
PS C:\> $b
1
2
3
意思是,您正在创建$x
的副本,该副本不再引用$testArr
中的项目
答案 1 :(得分:0)
iRon's helpful answer描述了问题的症结所在,即无法调整大小。如果要添加到集合中,则必须选择一个允许更改长度的集合类型。一些常见的可调整大小的类型包括通用列表和数组列表。一种允许您更改多维集合大小的方法是使一个[arraylist]
对象包含[int]
对象的一般列表。
[collections.arraylist]$testArr = [collections.generic.list[int]](1,2,3),[collections.generic.list[int]](4,5,6)
$testArr
1
2
3
4
5
6
$testArr.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True ArrayList System.Object
$testArr[0]
1
2
3
$testArr[0].GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True List`1 System.Object
$testArr[0].Add(0)
$testArr[0]
1
2
3
0
$testArr[1].Add(0)
$testArr[1]
4
5
6
0
您现在可以通过索引[0]
和[1]
来引用每个子集合,并相应地对其进行扩充。
答案 2 :(得分:0)
我会尽你所能,但要警告+ =会杀死幼犬。我猜你没有直接引用数组。
foreach ($i in 0,1) { $testarr[$i] += 0 }
$testarr
1
2
3
0
4
5
6
0
您还可以使其成为2个数组列表的数组。
$a = [Collections.ArrayList](1,2,3),[Collections.ArrayList](4,5,6)
$a[0].add(0)
$a[1].add(0)