检查javascript数组中的最后一项
check for the last item in a javascript array
我有这个数组,我通过使用$.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()方法,对第一个元素执行操作。
相关文章:
- 如何从对象数组中获取最后一项
- 为什么只有最后一项显示,而不是全部显示
- 删除最后一项jquery
- 为什么我的“for”循环只获取 html 中的最后一项
- 我无法将下拉列表的默认值设置为最后一项
- 流星批量插入仅插入最后一项
- 我怎么能知道元素是最后一项
- 如何删除WinJS组绑定列表的最后一项
- 使用handlers.js模板以数组中的最后一项为条件
- empty().append()追加循环中的最后一项
- jQuery只附加最后一项
- 将属性添加到 for 循环中的最后一项
- 如何按排序键顺序获取对象中的最后一项
- for 循环中的 addEventListener 始终添加到最后一项
- 从数组中删除最后一项
- CasperJS只从我的for循环中多次发布最后一项
- 在 JavaScript 中处理数组中的最后一项
- 胡子.js带有数组,最后一项除外
- 通过jQuery在最后一项之后插入
- JavaScript for 循环只返回数组中的最后一项