admin管理员组

文章数量:1178539

How can we check for the last iteration of a jQuery.each() loop? My loop is iterating on an object coming from a $.ajax request.

jQuery.ajax({
  url: "<?php echo $this->getUrl('xs4arabia/index/getFetchrOrderLogs/'); ?>",
  type: "GET",
  data: {
    tracking_id: tracking_id
  },
  dataType: "json",
  success: function(data) {
    jQuery.each(data, function(key, value) {
      console.log(value);
    })
  }
});

How can we check for the last iteration of a jQuery.each() loop? My loop is iterating on an object coming from a $.ajax request.

jQuery.ajax({
  url: "<?php echo $this->getUrl('xs4arabia/index/getFetchrOrderLogs/'); ?>",
  type: "GET",
  data: {
    tracking_id: tracking_id
  },
  dataType: "json",
  success: function(data) {
    jQuery.each(data, function(key, value) {
      console.log(value);
    })
  }
});
Share Improve this question edited Mar 6, 2020 at 15:34 Rory McCrossan 337k41 gold badges319 silver badges350 bronze badges asked Sep 8, 2016 at 14:33 OBAIDOBAID 1,5392 gold badges22 silver badges46 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 24

The first parameter passed to the each() handler function is the index of the current element in the array (although you've currently named it key). You can compare that to the length of the array to find out your current position:

$.each(data, function(index, value) {
  var isLastElement = index == data.length -1;
  if (isLastElement) {
    console.log('last item')
  }

  console.log(value);
};

Here's an additional example using the native forEach() method:

data.forEach((val, i) => {
  var isLastElement = index == data.length -1;
  if (isLastElement) {
    console.log('last item')
  }

  console.log(value);
});

the first parameter of the each function is equal to the index.

So, you can compare the index to the length of your data.

Look at this example using div tags :

$(document).ready(function(){
	var len = $('div').length;
	$('div').each(function(index){
  	if (index === (len - 1))
  		alert('Last index');
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div>1</div>
<div>2</div>
<div>3</div>

Here's another example using an object that contain an array property :

var data = {
	myArray:[1,2,3]
}

$(document).ready(function(){
	var len = data.myArray.length;
	$.each(data.myArray,function(index,value){
  	if (index === (len - 1))
  		alert(index);
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can check the length of data and compare it with the key (note that the first key is 0)

 jQuery.ajax({
        url: "<?php echo $this->getUrl('xs4arabia/index/getFetchrOrderLogs/'); ?>",
        type: "GET",
        data: {tracking_id: tracking_id},
        dataType: "json",
        success: function (data) {
        var arrLength = data.length;
        jQuery.each(data, function (key, value) {
              if( key == arrLength - 1 ) {
                  /* this is the last one */
              }
              console.log(value);
        },
 })

each passes into your function key and value. Check key(index) against the length of the data.

if (key == data.length- 1) {
              console.log('Last field');
          }

there is the answer for a list of class of form-group. If it is the last iteration of the forloop it will do nothing. If it is the other value it will check if there is not a bootstrap class of margin-bottom 3px already and will add it

$(".form-group").each(function(index, value) {
    var isLastElement = index == $(this).length;
    if (isLastElement) {
        console.log($(this));
    } else if (!$(this).hasClass("mb-3")) {
        $(this).addClass("mb-3");
    }
});

本文标签: javascriptCheck for last iteration in jQueryeachStack Overflow