检查javascript数组中的最后一项

Moh*_*iba 5 javascript arrays jquery loops

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

Jai*_*Jai 9

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

console.log(myArray.pop()); // logs the last item
Run Code Online (Sandbox Code Playgroud)

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


简单测试场景:

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

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


小智 6

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

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