检查 javascript 数组中的最后一项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23579994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:08:19  来源:igfitidea点击:

check for the last item in a javascript array

javascriptjqueryarraysloops

提问by Mohsen Shakiba

I have this array which I iterate through by using $.each(...). But I need to do something to the very last item in the array. so I need to know in the loop that if it's the last item, then do something. thanks a lot ;)

我有这个数组,我使用 $.each(...) 对其进行迭代。但是我需要对数组中的最后一项做一些事情。所以我需要在循环中知道如果它是最后一项,那么做一些事情。多谢 ;)

回答by Jai

you can use .pop()method:

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

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

Array.prototype.pop()The pop() method removes the last element from an array and returns that element.

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



Simple test scenario:

简单的测试场景:

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

so now you can store it in a var and use it.

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

回答by Easwar Raju

send index as parameter to the function

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

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

回答by Christian Landgren

Just add a second parameter to the function. This works both in jQuery and in native array.forEach method.

只需向该函数添加第二个参数即可。这在 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);
});

回答by David Battersby

You can access both the index and current Array value within the $.each callback.

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

Warning: using .pop() as suggested in other answers will directly delete the last item from your array and return the value. Not good if you need the array again later.

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

回答by commesan

Or use the reverse() method on the array and do your thing on the first element.

或者在数组上使用 reverse() 方法并在第一个元素上做你的事情。