理解 break, continue, return 和 exit

你们知道 “break”, “continue”, “return” 和 “exit”的作用吗? 它们是功能强大的语言结构体。下面通过一个测试函数来说明它们之间的不同。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
'Starting'
 
function Test-Function {
    $fishtank = 1..10
 
    Foreach ($fish in $fishtank)
    {
        if ($fish -eq 7)
        {
            break      # <- abort loop
            #continue  # <- skip just this iteration, but continue loop
            #return    # <- abort code, and continue in caller scope
            #exit      # <- abort code at caller scope
        }
 
        "fishing fish #$fish"
 
    }
    'Done.'
}
 
Test-Function
 
 
'Script done!'

你可以去掉其中某个关键字的注释,然后运行脚本来查看结果。
使用 break, 运行结果如下:

posted @ 2016-10-09 12:11  特洛伊-Micro  阅读(253)  评论(0编辑  收藏  举报