Looping over the last few entries of an array

做~自己de王妃 提交于 2021-01-28 05:38:18

问题


I'm trying to have a forEach loop over an array, but only the last few entries.

I'd know how to do this in a for loop, that'd look a bit like this:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 

/* This will loop over the last 3 entries */
for(var x = arr.length; x >= 7; x--){
    console.log(arr[x]);
}

Would there be any way of achieving the same results in a forEach loop?


回答1:


You can use slice() and reverse() methods and then forEach() loop on that new array.

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
arr.slice(-3).reverse().forEach(e => console.log(e))



回答2:


This is how you do it with forEach loop:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
arr.forEach((element, index) => {
  if(index>7) console.log(arr[index]);
})



回答3:


You could take a classic approach by taking the count of the last elements and use it as counter and an offset for the index.

Then loop with while by decrementing and checking the counter.

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    last = 3,
    offset = array.length - last;
    
while (last--) {
    console.log(array[last + offset]);
}


来源:https://stackoverflow.com/questions/48611013/looping-over-the-last-few-entries-of-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!