简体   繁体   中英

javascript - how to get the last loop iteration if data length is unknown

I have a loop in JavaScript:

data is just a list of strings. 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?

如果只需要最后一个元素,则无需迭代整个循环。

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM