为什么PowerShell会自动展平数组? [英] Why does PowerShell flatten arrays automatically?

查看:88
本文介绍了为什么PowerShell会自动展平数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些pwsh代码

I've written some pwsh code

"a:b;c:d;e:f".Split(";") | ForEach-Object { $_.Split(":") }
# => @(a, b, c, d, e, f)

但是我想要这个

// in javascript
"a:b;c:d;e:f".split(";").map(str => str.split(":"))
[ [ 'a', 'b' ], [ 'c', 'd' ], [ 'e', 'f' ] ]

嵌套数组

@(
    @(a, b),
    @(c, d),
    @(e, f),
)

为什么?以及我该怎么办

Why? and what should I do

推荐答案

使用,(PowerShell的数组构造运算符)的一元形式:

Use the unary form of ,, PowerShell's array-construction operator:

"a:b;c:d;e:f".Split(";") | ForEach-Object { , $_.Split(":") }

这样,由$_.Split(":")返回的数组实际上按原样作为 array 输出,而不是让其元素逐个输出 ,这种情况会发生默认情况下,在PowerShell管道中.

That way, the array returned by $_.Split(":") is effectively output as-is, as an array, instead of having its elements output one by one, which happens by default in a PowerShell pipeline.

,创建一个-瞬态-包装器数组,其唯一元素是要输出的数组.然后,PowerShell 对输出中的包装器数组进行解包,将包装后的数组传递通过.

, creates a - transient - wrapper array whose only element is the array you want to output. PowerShell then unwraps the wrapper array on output, passing the wrapped array through.

这篇关于为什么PowerShell会自动展平数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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