从函数返回多维数组 [英] Return Multidimensional Array From Function

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

问题描述

在将现有的vbs脚本转换为PowerShell脚本时遇到了一些问题.我在这里用一些伪代码而不是原始代码进行了说明.在示例1中,我在数组中只有1组元素,将数组变量返回给函数时,它将仅显示P.

I encountered some issue in converting my existing vbs script to PowerShell script. I have illustrate here with some dummy codes instead of my original code. In example 1, I only have 1 set of elements in the array, upon return the array variable to the function, it will only display P.

但是在示例2中,在数组中有2个元素集的情况下,将数组变量返回给函数后,它将正确显示元素.

However in example 2, where I have 2 set of elements in the array, upon return the array variable to the function, it will display the elements properly.

如果在示例1和2中在函数内部打印数组,则获取结果没有任何问题.

If you print the array inside the function in example 1 and 2. There isn't any issue in getting the results.

我已经用Google搜索,但找不到任何解决方案.在此先感谢您的帮助.

I have googled and not able to find any solution to it. Many thanks in advance for the kind help.

示例1:

function testArray {
    $array1 = @()
    $array1 += ,@("Apple","Banana")

    return $array1
}
$array2 = testArray
Write-Host $array2[0][1]

结果为"P".

示例2:

function testArray {
    $array1 = @()
    $array1 += ,@("Apple","Banana")
    $array1 += ,@("Orange","Pineapple")

    return $array1
}
$array2 = testArray
Write-Host $array2[0][0]

结果是苹果".

推荐答案

PowerShell展开从函数返回的数组.使用逗号运算符(,,一元数组构造运算符)包装返回的数组将其放在另一个数组中,该数组将在返回时展开,而保留嵌套数组的完整性.

PowerShell unrolls arrays returned from a function. Prepend the returned array with the comma operator (,, unary array construction operator) to wrap it in another array, which is unrolled on return, leaving the nested array intact.

function testArray {
    $array1 = @()
    $array1 += ,@("Apple","Banana")

    return ,$array1
}

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

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