Why the 1st example gets different results than the following 2 in powershell
$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
I think on #powershell IRC we have worked it out, Here is another example that demonstrates the danger of breaking with the comma on the following line rather than the top line when listing multiple items in an array over multiple lines.
$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 }
produces
20 20 20 20 20 20 -------- 20 20 20 1 20 20
In fact rather that using nested arrays that may complicate it here 开发者_JS百科is a simple array of integers
$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() }
and the results
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
I'm curious how people will explain this. I think I understand it now, but would have trouble explaining it in a concise understandable fashion, though the above example goes somewhat towards that goal.
I can explain the first example, but not the second two. The unary comma operator (see http://rkeithhill.wordpress.com/2007/09/24/effective-powershell-item-8-output-cardinality-scalars-collections-and-empty-sets-oh-my/) creates an array with one member, so ,$b
creates an array containing ($b
); ,$b,$b
creates an array containing (,$b
and $b
).
The second two examples, I believe, are creating an array with one-element containing $b,$b
. Then the one-element array gets flattened, yielding just $b,$b
.
If somebody can post a link definitively explaining the behavior of the second two examples, I'd love to see it!
精彩评论