String Iteration, Is it possible

Hi again guys, 

I have now got a long list of code, that I would like to iterate - modifying the end of an App.Property key ( which I assume is a "string"),

The code is like this

}else if(Application.getValue("wptn") > 6) {
$.mWaypoints.add(Application.getValue("w7"));
$.mWaypoints.add(Application.getValue("lat7"));
$.mWaypoints.add(Application.getValue("long7"));
}else if(Application.getValue("wptn") > 7) {
$.mWaypoints.add(Application.getValue("w8"));
$.mWaypoints.add(Application.getValue("lat8"));
$.mWaypoints.add(Application.getValue("long8"));

where "wptn" is a number, and is the number of iterations I need to run, starting at 1

I need to be able to add the iteration number to the end of the partial getValue 

Do you think this is possible?

for( var i=1; i < (Application.getValue("wptn")+1); i +=1) { 

$.mWaypoints.add(Application.getValue("w"+"i"));

}

  • What you're describing is string concatenation (joining two strings), not "string iteration".

    The code you're looking for is:

    "w" + i

    In this case, i is implicitly converted to a string, then appended to "w".

    This can easily be tested without actually using properties with code such as this:

            for (var i = 1; i <= 10; i++) {
                System.println("w" + i);
            }

    This code will print:

    w1
    w2
    w3
    w4
    w5
    w6
    w7
    w8
    w9
    w10

    If you want to use Application.getValue() as in your example above, you may need some guard code or a helper function to ensure that the return value is indeed a number.

    For example, in the following code, if the "wptn" property doesn't exist for some reason, then the code will crash because you can't add null and 1.

    for( var i=1; i < (Application.getValue("wptn")+1); i +=1) {

    Furthermore, Application.getValue shouldn't be called on every iteration of the loop, as it could be expensive in terms of CPU and I/O. Since the value is not expected to change, you can call it once and store the result in a variable.

    For example:

    var wptn = Application.getValue("wptn");
    
    if (wptn != null) {
        for (var i = 1; i <= wptn; i++) {
            var w = Application.getValue("w" + i);
            if (w != null) {
                $.mWaypoints.add(w);
            } else {
                // handle non-existent waypoint (System.println?)
            }
        }
    } else {
        // handle non-existent waypoint count (System.println?)
    }

  • Thanks for your response, I learned more today!