$b = (2,3) $myarray1 = @(,$b,$b) $myarray1[0].length #this will be 1 $myarray1[1].length $myarray2 = @( ,$b ,$b ) $myarray2[0].length #this will be 2 $myarray[1].length $myarray3 = @(,$b ,$b ) $myarray3[0].length #this will be 2 $myarray3[1].length
UPDATE
我认为在#powershell IRC上我们已经解决了这个问题,这是另一个例子,它演示了在多行中列出数组中的多个项目时,在下一行而不是顶行上使用逗号的危险.
$b = (1..20)
$a = @( $b, $b ,$b,
$b, $b ,$b)
for($i=0;$i -lt $a.length;$i++)
{
$a[$i].length
}
"--------"
$a = @( $b, $b ,$b
,$b, $b ,$b)
for($i=0;$i -lt $a.length;$i++)
{
$a[$i].length
}
产生
20 20 20 20 20 20 -------- 20 20 20 1 20 20
实际上,使用可能使其复杂化的嵌套数组是一个简单的整数数组
$c = @( 1 , 2 ,
3 , 4 )
for($i=0;$i -lt $c.length;$i++)
{
$c[$i].gettype()
}
"---------"
$c = @( 1 , 2
, 3 , 4 )
for($i=0;$i -lt $c.length;$i++)
{
$c[$i].gettype()
}
和结果
IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Int32 System.ValueType True True Int32 System.ValueType True True Int32 System.ValueType True True Int32 System.ValueType --------- True True Int32 System.ValueType True True Int32 System.ValueType True True Object[] System.Array True True Int32 System.ValueType
我很好奇人们会如何解释这一点.我想我现在明白了,但是以简洁易懂的方式解释它会有困难,尽管上面的例子有点朝着这个目标.
我可以解释第一个例子,但不能解释后两个。一元逗号运算符(请参阅http://rkeithhill.wordpress.com/2007/09/24/ effective-powershell -item-8-output-cardinality-scalars-collections-and-empty-sets-oh-my/ )创建一个只有一个成员的数组,因此,$b创建一个包含 ( $b) 的数组;,$b,$b创建一个包含 (,$b和$b) 的数组。
我相信,后两个示例正在创建一个包含单元素的数组$b,$b。然后单元素数组被展平,仅产生$b,$b.
如果有人可以发布一个链接来明确解释后两个示例的行为,我很乐意看到它!