首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么'continue‘在Foreach-Object中的行为类似于'break’?

为什么'continue‘在Foreach-Object中的行为类似于'break’?
EN

Stack Overflow用户
提问于 2011-10-14 04:24:27
回答 4查看 79.4K关注 0票数 138

如果我在PowerShell脚本中执行以下操作:

代码语言:javascript
运行
复制
$range = 1..100
ForEach ($_ in $range) {
    if ($_ % 7 -ne 0 ) { continue; }
    Write-Host "$($_) is a multiple of 7"
}

我得到了以下内容的预期输出:

代码语言:javascript
运行
复制
7 is a multiple of 7
14 is a multiple of 7
21 is a multiple of 7
28 is a multiple of 7
35 is a multiple of 7
42 is a multiple of 7
49 is a multiple of 7
56 is a multiple of 7
63 is a multiple of 7
70 is a multiple of 7
77 is a multiple of 7
84 is a multiple of 7
91 is a multiple of 7
98 is a multiple of 7

但是,如果我使用管道和ForEach-Objectcontinue似乎会跳出管道循环。

代码语言:javascript
运行
复制
1..100 | ForEach-Object {
    if ($_ % 7 -ne 0 ) { continue; }
    Write-Host "$($_) is a multiple of 7"
}

我是否可以在仍然使用ForEach--like的同时获得一个continue对象行为,这样我就不必中断我的管道了?

EN

Stack Overflow用户

回答已采纳

发布于 2011-10-14 14:07:43

只需使用return而不是continue。此returnForEach-Object在特定迭代中调用的脚本块返回,因此,它在循环中模拟continue

代码语言:javascript
运行
复制
1..100 | ForEach-Object {
    if ($_ % 7 -ne 0 ) { return }
    Write-Host "$($_) is a multiple of 7"
}

在重构时,有一个问题需要牢记。有时,人们希望使用ForEach-Object cmdlet将foreach语句块转换为管道(它甚至具有别名foreach,这有助于简化转换,也容易出错)。所有continue都应替换为return

附言:不幸的是,在ForEach-Object中模拟break并非易事。

票数 184
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7760013

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档