Level: Beginner
Knowledge Required:
- For Each Loop
- For Next Loop
- Arrays
Description:
It is observed that when we use For Each Loop to iterate through a String Array and perform some action with each item then this change does NOT affect the String Array itself. Consider the following code
Dim strArray() As String = {"First Item", "Second Item", "Third Item"}
' First we are trying to add some more
' text with each item in array
For Each strItem As String In strArray
strItem &= " some data"
Next
' Now again iterate through this array to see
' whether the changes has been made or not
For Each strItem As String In strArray
Debug.Print(strItem)
Next
The output of above code will be
First Item
Second Item
Third Item
As you can see the output, there is NO change in items since each time value is copied into the variable and that variable was changed NOT the Array item. So to make changes in each item we will be using the For Next loop as,
Dim strArray() As String = {"First Item", "Second Item", "Third Item"}
' First we are trying to add some more ' text with each item in array
For i As Integer = 0 To strArray.Length - 1
strArray(i) &= " some data"
Next
' Now again iterate through this array to see
' whether the changes has been made or not
For Each strItem As String In strArray
Debug.Print(strItem)
Next
The output of above code will be
First Item some data
Second Item some data
Third Item some data
2 comments:
Is there a reason why 'For Each' doesn't save the changes to an array but the 'For Next' loop will?
For each loop copies the value of Array item into another string variable, that is why when you append more text it is appended in that other variable NOT in array item. While when we do For Next, we pick the array item and we do changes in array item.
Post a Comment