Multidimensional array initialization seems sensitive to whitespace

ぐ巨炮叔叔 提交于 2019-12-23 15:39:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!