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

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

问题描述

我在将现有的 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.

我用谷歌搜索过,但找不到任何解决方案.非常感谢您的帮助.

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天全站免登陆