检查javascript数组中的最后一项

时间:2014-05-10 10:38:51

标签: javascript jquery arrays loops

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

5 个答案:

答案 0 :(得分:8)

您可以使用.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中并使用它。

答案 1 :(得分:2)

将index作为参数发送到函数

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

您可以访问$ .each回调中的索引和当前数组值。

警告:使用其他答案中建议的.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);
  }
});

答案 4 :(得分:0)

只需在函数中添加第二个参数即可。这适用于jQuery和本机array.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);
});