问题描述
我注意到这两个声明之间的区别,只是逗号的位置发生了变化。
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'))
在这种情况下, $ a.length
的结果为2, $ b.length
的结果为3。 $ b 已被扁平化。
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?
顺便说一下, $ 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
推荐答案
, 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.
这是因为 @('a','b')
将两个字符串 a
和 b
推入数组 $ b
,而您强迫 @('c','d')
进入 $ b
作为使用逗号的数组
。
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.
示例:
$b = @( @('a','b')
, @('c','d'))
$b | foreach { Write-Host "Item: $_"}
输出:
Item: a
Item: b
Item: c d
如果您查看类型:
$b | foreach { $_.GetType()}
您得到:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
True True String System.Object
True True Object[] System.Array
强制 $ b
包含两个数组
,使用逗号二进制运算符:
To force $b
to contain two arrays
, use the comma binary operator:
$b = @(@('a','b'),@('c','d'))
这篇关于多维数组初始化似乎对空白敏感的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!