Powershell:多维数组作为函数的返回值
我在 PowerShell 中的二维数组方面遇到了一些问题。 这就是我想要做的:
我创建一个应该返回二维数组的函数。调用该函数时,我希望返回值是一个新的二维数组。
为了更好地理解,我在下面添加了一个示例函数:
function fillArray() {
$array = New-Object 'object[,]' 2,3
$array[0,0] = 1
$array[0,1] = 2
$array[0,2] = 3
$array[1,0] = 4
$array[1,1] = 5
$array[1,2] = 6
return $array
}
$erg_array = New-Object 'object[,]' 2,3
$erg_array = fillArray
$erg_array[0,1] # result is 1 2
$erg_array[0,2] # result is 1 3
$erg_array[1,0] # result is 2 1
结果不是我所期望的。我想以与函数中声明的方式相同的方式返回信息。因此,我希望 $erg_array[0,1]
给我 2
而不是我通过上面的代码收到的 1,2
。我怎样才能实现这个目标?
I've got some problems with two-dimensional arrays in PowerShell.
Here's what I want to do:
I create a function that is supposed to return a two-dimensional array. When invoking the function I want the return value to be a new two-dimensional array.
For a better understanding I've added an example function, below:
function fillArray() {
$array = New-Object 'object[,]' 2,3
$array[0,0] = 1
$array[0,1] = 2
$array[0,2] = 3
$array[1,0] = 4
$array[1,1] = 5
$array[1,2] = 6
return $array
}
$erg_array = New-Object 'object[,]' 2,3
$erg_array = fillArray
$erg_array[0,1] # result is 1 2
$erg_array[0,2] # result is 1 3
$erg_array[1,0] # result is 2 1
The results are not what I expect. I want to return the information in the same way as declared in the function. So I would expect $erg_array[0,1]
to give me 2
instead of the 1,2
I receive with the code above. How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了完全按原样返回数组而不“展开”,请使用逗号运算符(请参阅
help about_operators
),
创建一个包含单个项目的数组(这是我们的大批)。这个 1 项数组在返回时展开,但只有一层,因此结果恰好是一个对象,即我们的数组。如果没有,
我们的数组本身就会展开,返回的是它的项,而不是数组。这种在返回时使用逗号的技术也应该与其他一些集合一起使用(如果我们想返回一个集合实例,而不是它的项目)。In order to return the array exactly as it is without "unrolling" use the comma operator (see
help about_operators
)The
,
creates an array with a single item (which is our array). This 1-item array gets unrolled on return, but only one level, so that the result is exactly one object, our array. Without,
our array itself is unrolled, its items are returned, not the array. This technique with using comma on return should be used with some other collections as well (if we want to return a collection instance, not its items).这个端口真正缺少的是每个人都在寻找的东西。如何从一个函数中获取多个内容。好吧,我将分享每个人都想知道谁搜索过并发现这个的内容,希望它能回答这个问题。
What is really missing in this port is what everyone is looking for. How to get more than one thing out of a function. Well I am going to share what everyone wants to know who has searched and found this hoping it will answer the question.