user2997555
user2997555

Reputation: 11

String control in loops

I have a big question. I have many Strings in my Programm and want to check these Strings on there values. I wrote a Loop for it, but insted of the Definition of an String he is creating a new value. It's basicly really difficult to discribe, also because i am basicly German. But i can give you my current code, so maybee you will see what I mean:

{
  var Loch1G = $('#m1-Rundenanalyse-Datum').val();  //In the strings just the number is changing
  var Loch2G = $('#m1-Rundenanalyse-Turnier').val();
  x=1
  while (x <= 2) { 

    if ("Loch" + x + "G" == ""){    //Next String is genrated (x=x+1)
    alert("Eingabe war leer");
    }
  x=x+1
  }
}

How can I solve this?

Upvotes: 1

Views: 54

Answers (1)

David Thomas
David Thomas

Reputation: 253308

I'd suggest using an array to store the values you want to check:

var lochs = [];
lochs.push($('#m1-Rundenanalyse-Datum').val());
lochs.push($('#m1-Rundenanalyse-Turnier').val());

for (var i = 0, len = lochs.length; i < len; i++){
    if (lochs[i] == ''){
        alert("Eingabe war leer");
    }
}

JS Fiddle demos: passes (no alert), fails (alert)

This suggestion is based on my presumption that you're trying to create the names of the vars you want to check, which won't work, whereas this approach lets you store all values (however many) in the same array and then iterate over that array to find any values that are equal to an empty string.

If you really want to stick with your current approach, you could do the following:

{
  window.Loch1G = $('#m1-Rundenanalyse-Datum').val();  //In the strings just the number is changing
  window.Loch2G = $('#m1-Rundenanalyse-Turnier').val();
  var x=1;
  while (x <= 2) { 

    if (window["Loch" + x + "G"] == ""){    //Next String is genrated (x=x+1)
    alert("Eingabe war leer");
    }
  x=x+1;
  }
}

But I can't think why you'd want to; plus the use of global variables is poor practice as it explicitly makes those variables available to every closure within the document, which allows them to be easily, and accidentally, overwritten.

In a reasonably up-to-date browser, that implements Array.prototype.every, you could dispense with the explicit iteration:

var lochs = [];
lochs.push($('#m1-Rundenanalyse-Datum').val());
lochs.push($('#m1-Rundenanalyse-Turnier').val());

if (!lochs.every(function(a){ return a !== ''; })) {
    alert("Eingabe war leer");
}

JS Fiddle demos: passes (no alert), fails (alerts).

Upvotes: 2

Related Questions