问题
I noticed a difference between those two declarations where only the position of the comma changes:
$a = @( @('a','b'),
@('c','d'))
$b = @( @('a','b')
, @('c','d'))
In this case, $a.length
evaluates to 2 and $b.length
evaluates to 3. The first sub-array of $b
has been flattened.
Is this a feature and where can I find its documentation?
By the way, $PSVersionTable
:
Name Value
---- -----
PSVersion 4.0
WSManStackVersion 3.0
SerializationVersion 1.1.0.1
CLRVersion 4.0.30319.42000
BuildVersion 6.3.9600.16406
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion 2.2
回答1:
, Comma operator
As a binary operator, the comma creates an array. As a unary
operator, the comma creates an array with one member. Place the
comma before the member.
Source.
Its because @('a','b')
will push two strings a
and b
into the array $b
whereas you force @('c','d')
to get pushed into $b
as an array
using a comma.
Example:
$b = @( @('a','b')
, @('c','d'))
$b | foreach { Write-Host "Item: $_"}
Output:
Item: a
Item: b
Item: c d
And if you look at the types:
$b | foreach { $_.GetType()}
You get:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
True True String System.Object
True True Object[] System.Array
To force $b
to contain two arrays
, use the comma binary operator:
$b = @(@('a','b'),@('c','d'))
来源:https://stackoverflow.com/questions/37721698/multidimensional-array-initialization-seems-sensitive-to-whitespace