检查javascript数组中的最后一项
我使用$.each(…)遍历这个数组。 但是我需要对数组中的最后一项做些什么。 所以我需要在循环中知道,如果它是最后一项,那么就做点什么。 非常感谢;) 或者对数组使用reverse()方法,并对第一个元素执行操作。您可以使用检查javascript数组中的最后一项,javascript,jquery,arrays,loops,Javascript,Jquery,Arrays,Loops,我使用$.each(…)遍历这个数组。 但是我需要对数组中的最后一项做些什么。 所以我需要在循环中知道,如果它是最后一项,那么就做点什么。 非常感谢;) 或者对数组使用reverse()方法,并对第一个元素执行操作。您可以使用.pop()方法: console.log(myArray.pop()); // logs the last item 方法从数组中删除最后一个元素并返回该元素 简单测试场景: var myArray = [{"a":"aa"},{"b":"bb"},{"c":"cc"
.pop()
方法:
console.log(myArray.pop()); // logs the last item
方法从数组中删除最后一个元素并返回该元素
简单测试场景:
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
}
});
您可以访问$.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);
}
});
只需在函数中添加第二个参数。这在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);
});
你能发布你的数组吗。