How to loop a 2 array using a for each… next loop?

后端 未结 1 939
野的像风
野的像风 2021-01-24 10:45

I have this simple basic code of VBScript using For Each...Next Loop

<%
Dim cars(2)
cars(0)=\"Volvo\"
         


        
相关标签:
1条回答
  • 2021-01-24 11:24

    Use a For instead of For Each and output the array at the same index in both arrays. You have to pick one of the arrays to use UBound() off, just make surwe both arrays have the same number of element or you will end up with Sub Script out of Range errors.

    Dim cars: cars = Array("Volvo", "Saab", "BMW")
    Dim fruits: fruits = Array("Apple", "Orange", "Banana")
    
    Dim i: i = 0
    
    For i = 0 To UBound(cars)
      Call Response.Write(cars(i) & " " & fruits(i))
    Next
    

    Output:

    Volvo Apple
    Saab Orange
    BMW Banana
    

    Another approach which avoids the issues with Sub Script out of Range errors is to use a Multi Dimensional Array.

    Dim things(2, 1)
    Dim i: i = 0
    
    things(0, 0) = "Volvo"
    things(0, 1) = "Apple"
    things(1, 0) = "Saab"
    things(1, 1) = "Orange"
    things(2, 0) = "BMW"
    things(2, 1) = "Banana"
    
    For i = 0 To UBound(things, 1)
      Call Response.Write(things(x, 0) & " " & things(x, 1))
    Next
    

    Output:

    Volvo Apple
    Saab Orange
    BMW Banana
    

    Another approach is almost an amalgamation of the first two, it uses a Single Dimension Array but nests Single Dimension Arrays inside it.

    Dim things(2)
    
    things(0) = Array("Volvo", "Apple")
    things(1) = Array("Saab", "Orange")
    things(2) = Array("BMW", "Banana")
    
    For Each thing In things
      Call Response.Write(thing(0) & " " & thing(1))
    Next
    

    Output:

    Volvo Apple
    Saab Orange
    BMW Banana
    
    0 讨论(0)
提交回复
热议问题