最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript - Is it possible to limit the results given by a forEach loop? - Stack Overflow

programmeradmin2浏览0评论

I have a very long JSON array that I fetch using a forEach loop where I need to display only the last 5 elements.

  array.forEach(showOnlyFiveElements => {
   //only 5 elements should be show here
  });

Can't it be done using a forEach ? Or I should go for something different?

I have a very long JSON array that I fetch using a forEach loop where I need to display only the last 5 elements.

  array.forEach(showOnlyFiveElements => {
   //only 5 elements should be show here
  });

Can't it be done using a forEach ? Or I should go for something different?

Share Improve this question asked May 2, 2017 at 11:47 Folky.HFolky.H 1,2044 gold badges16 silver badges40 bronze badges 4
  • 5 array.slice(0, 5).forEach – Tushar Commented May 2, 2017 at 11:48
  • you can use if inside forEach – Naveed Aheer Commented May 2, 2017 at 11:49
  • Use for loop starting at the end and counting down (i--) with correct condition – Esko Commented May 2, 2017 at 11:49
  • 4 @Andreas .slice(-5)..... :) – Tushar Commented May 2, 2017 at 11:49
Add a comment  | 

1 Answer 1

Reset to default 45

You could use Array#slice with negative value for the last items.

array.slice(-5).forEach()
发布评论

评论列表(0)

  1. 暂无评论