close

For Each 迴圈的真正用途

For Each 迴圈的語法事實上是對一個陣列的每一個值做運算。因此他後面所放置的必須是一個集合──也就是陣列型態。

 

For Each 的語法是"For Each 變數 As 型態 In 陣列"。

]Dim testInteger() As Integer = {0, 1, 3, 6, 10}

]For Each testFor As Integer In testInteger

]MsgBox(testFor) //For Each 函式把每一個陣列值都找出來,MsgBox 依序顯示"0"、"1"、"3"、"6"、"10"。

]Next

 

其實,For Each 只是為了程式的美觀性而存在的,她可以用原本的For 迴圈來寫出:

]Dim testInteger() As Integer = {0, 1, 3, 6, 10}

]For testIndex As Integer = LBoound(testInteger) To UBound(testInteger) Step 1

]MsgBox(testInteger(testIndex)) //這樣也可以達到上例的效果。

]Next

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 GPhettoH 的頭像
    GPhettoH

    歇息,等待明日的天空

    GPhettoH 發表在 痞客邦 留言(0) 人氣()