Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop check if on last iteration?

Tags:

javascript

How do I check if I'm on the last iteration of this loop? I'm sorry for asking this question. I'm used to programming in VB.NET and javascript seems very cryptic by nature.

if (QuerySplit.length > 1) {
   var NewQuery
   for (i=0; i<QuerySplit.length; i++)
   {
       // if we're not on the last iteration then
       if (i != QuerySplit.length) {
           // build the new query
           NewQuery = QuerySplit[i].value + " AND "
       }
    }
}
like image 439
Neil Avatar asked Jun 25 '13 18:06

Neil


People also ask

How do you know if loop is last iteration?

Use a counter variable and check when the counter value is zero then it is the first iteration and when the counter value is length-1 then it is the last iteration.

How do I find the last iteration in Python?

To detect the last item in a list using a for loop: Use the enumerate function to get tuples of the index and the item. Use a for loop to iterate over the enumerate object. If the current index is equal to the list's length minus 1 , then it's the last item in the list.

How do I get the last index of a for loop?

You can always find the last index with len(string) -1. for l in range(-(len(st)) + 1, 1): Which makes a list of numbers that are the length of the string you input, but backwards and negative. Then, when you refer to them in the loop, you simply use abs(l) to get the absolute value.

Does for loop work on iteration?

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.


2 Answers

Your i is always smaller than QuerySplit.length - that's your loop condition. In the last iteration it will have a value of QuerySplit.length-1, that's what you can check against:

if (i < QuerySplit.length - 1)

Btw, you'd do better to use the join Array method for what you're trying to do:

var NewQuery = QuerySplit.map(function(x){return x.value;}).join(" AND ");
like image 102
Bergi Avatar answered Sep 18 '22 20:09

Bergi


Take note that you need var NewQuery = ""; and check for length - 1. Also, the last if statement is just a guess of what you probably want to do:

if (QuerySplit.length > 1) {
  var NewQuery = "";
  for (i = 0; i < QuerySplit.length; i++) {
    // if we're not on the last iteration then
    if (i != QuerySplit.length - 1) {
      // build the new query
      NewQuery += QuerySplit[i].value + " AND "
    } else {
      NewQuery += QuerySplit[i].value;
    }
  }
}

If QuerySplit.length is 4, then:

0, 1, 2, 3

...are the indexes. So you want to check for when the index is 3 and that's your last iteration.

like image 37
David Sherret Avatar answered Sep 18 '22 20:09

David Sherret