我有一个数组,目前它在过滤后只包含今天的比赛后从数组中获取前 6 个项目。
fixtures.filter(fixture => {
return fixture.date === today;
}).slice(0, 6);
这很好用,但我想在过滤后从数组中获取最后 6 项。我尝试了以下方法,但它对我不起作用。
fixtures.filter((fixture, index, arr) => {
return fixture.date === today;
}).slice(Math.max(arr.length - 6, 1));
这是说 arr
是未定义的。有没有办法在一条链中做到这一点?
最佳答案
您可以使用 .slice(-6)
获取数组的最后 6 个元素。 A negative index can be used, indicating an offset from the end of the sequence .
fixtures.filter(fixture => {
return fixture.date === today;
}).slice(-6);
关于javascript - 在过滤原始数组后从数组 js 中获取最后 6 个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54692890/