Know the last index of a .each

1

I'm running a .each and would like the last position to have a alert . For this I am trying to get the last position of index :

if (index == len - 1) {
    alert("Última posição");
}

Complete code:

$.getJSON("/Contrato/CriarCopiarContrato", { agrupamento: $("#listaAgrupamentos").val() },
   function (result) {
      $.each(result, function (index, itemData) {
          if (index == len - 1) {
              alert("ultima");
          }
      });
});
    
asked by anonymous 23.07.2014 / 17:45

2 answers

5

Simply retrieve the length - length of your result. The code is shown below:

$.getJSON("/Contrato/CriarCopiarContrato", { agrupamento: $("#listaAgrupamentos").val() },
   function (result) {
      var len = result.length;
      $.each(result, function (index, itemData) {
          if (index == len - 1) {
              alert("ultima");
          }
      });
});
    
23.07.2014 / 17:50
0

In addition to the above forms, since you are using JQuery, you can use the .last ()

Example:

var a = [1,2,3,4];
var lastEl = $(a).last()[0];

Source: link

    
23.07.2014 / 17:56