[英]javascript - how to get the last loop iteration if data length is unknown
I have a loop in JavaScript: 我在JavaScript中有一个循环:
data
is just a list of strings. data
只是一个字符串列表。 I don't know its length, because data is coming dynamically. 我不知道它的长度,因为数据是动态产生的。 This is my loop: 这是我的循环:
for (var i=1; i < data.length; i++) {
//how do i catch the last string in the list in loop?
};
it is important that i catch the last object inside loop 重要的是我要捕获循环中的最后一个对象
is there any this.last()
thing which gives me the last iteration? 有没有this.last()
可以给我最后一次迭代的东西?
如果只需要最后一个元素,则无需迭代整个循环。
var last = data[data.length - 1];
To simply capture the last element in an array, use: 要简单地捕获数组中的最后一个元素,请使用:
var lastItem = data[data.length - 1];
Or to create a new array containing only the last element, use this: 或创建一个仅包含最后一个元素的新数组,请使用以下命令:
var lastItem = data.slice(-1);
You could check if data[i+1] == undefined
inside the loop to find out when you are in the last loop iteration. 您可以检查循环内部if data[i+1] == undefined
,以了解您何时处于上一次循环迭代中。
When you have no real reason to loop through the array, you can use data[data.length - 1]
to access the last entry of the array. 当您没有真正的理由遍历数组时,可以使用data[data.length - 1]
访问数组的最后一个条目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.