powershell - 从函数中的 Powershell 循环提前返回
问题描述
我正在尝试制作一个简单的“合并”功能,但在使用 Powershell 返回语法时遇到了困难
尝试:
function coalesce {
foreach($item in $args) {
if ($item) {
return $item
break # also tried continue and exit
}
}
}
coalesce($nil,2,3)
2
3
function coalesce {
ForEach-Object -InputObject $args { If($_) { return $_; exit } } # also tried continue and break
}
coalesce($nil,2,3)
2
3
那么如何return
在任何其他编程语言中模拟退出函数的循环内部呢?
解决方案
在powershell中,如果你调用一个用逗号分隔的项目包裹的parens的函数,你会得到一个对象。[ grin ] 您的函数正在运行并返回三个对象的数组。因此,使用三个输入调用该函数 的正确方法是......
coalesce $Null 2 3
另请注意,这$nil
不是$Null
......它是一个新变量nil
,其中没有任何内容 - 换句话说,其中的值$Null
。
推荐阅读
- swift - 如何修复 IBOutlet 连接与 main.storyboard 错误?
- excel - 在网页上提交数据后查询未重定向到原始 URL
- qt - 在 eglfs 模式下,来自主题的图标在 QML 中不起作用
- javascript - 意外的节点类型:预期类型时发现 EXPR:LABELED_ARG
- flutter - Flutter Swiper on tap 抛出 Failed assertion
- java - 无法在 JSP 上显示对象会话的属性
- mysql - 无法将核心实体添加到 Mysql 中的链接表
- python - 如何使用 Python 根据当前颜色更改按钮的背景颜色?
- c# - AgileDotNet 混淆器弄乱了 httpClient.PostAsync
- php - 无法通过 OsTicket api 创建票证(格式错误的 JSON)