Powershell:多维数组作为函数的返回值 [英] Powershell: Multidimensional array as return value of function

查看:44
本文介绍了Powershell:多维数组作为函数的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 PowerShell 中遇到了一些二维数组问题.这是我想要做的:

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

结果不是我所期望的.我想以与函数中声明的方式相同的方式返回信息.所以我希望 $erg_array[0,1] 给我 2 而不是我用上面的代码收到的 1,2 .我怎样才能做到这一点?

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?

推荐答案

为了在不展开"的情况下完全返回数组,请使用逗号运算符(请参阅help about_operators)

In order to return the array exactly as it is without "unrolling" use the comma operator (see help about_operators)

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

    , $array # 'return' is not a mistake but it is not needed
}

# get the array (we do not have to use New-Object now)
$erg_array = fillArray

$erg_array[0,1] # result is 2, correct
$erg_array[0,2] # result is 3, correct
$erg_array[1,0] # result is 4, correct

, 创建一个包含单个项目的数组(这是我们的数组).这个 1 项数组在返回时展开,但只有一层,因此结果恰好是一个对象,即我们的数组.没有 , 我们的数组本身被展开,它的项目被返回,而不是数组.这种在返回时使用逗号的技术也应该用于其他一些集合(如果我们想返回一个集合实例,而不是它的项目).

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).

这篇关于Powershell:多维数组作为函数的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆