检查javascript数组中的最后一项

check for the last item in a javascript array

本文关键字:一项 最后 javascript 数组 检查      更新时间:2023-09-26

我有这个数组,我通过使用$.each(…)来迭代。但是我需要对数组的最后一项做点什么。所以我需要在循环中知道,如果它是最后一项,那么就做点什么。非常感谢;)

您可以使用.pop()方法:

console.log(myArray.pop()); // logs the last item

array .prototype.pop() pop()方法从数组中移除最后一个元素并返回该元素。


简单测试场景:

var myArray = [{"a":"aa"},{"b":"bb"},{"c":"cc"}];
var last    = myArray.pop();
console.log(last); // logs {"c":"cc"}

所以现在你可以将它存储在var中并使用它

将索引作为参数发送给函数

$.each(arr, function(index){
    if(index == (arr.length - 1)){
        // your code
    }
});

只需向函数添加第二个参数。这在jQuery和原生数组中都有效。forEach方法。

$.each(arr, function(item, i){
  if (i === arr.length-1) doSomething(item);
});
arr.forEach(function(item, i){
  if (i === arr.length-1) doSomething(item);
});

可以在$中访问索引和当前Array值。每个回调。

警告:使用其他答案中建议的.pop()将直接从数组中删除最后一项并返回值。如果你以后还需要这个数组,那就不好了。

// an Array of values
var myarray = ['a','b','c','d'];
$.each(myarray, function(i,e){
  // i = current index of Array (zero based), e = value of Array at current index
  if ( i == myarray.length-1 ) {
    // do something with element on last item in Array
    console.log(e);
  }
});

或者对数组使用reverse()方法,对第一个元素执行操作。