javascript - 在过滤原始数组后从数组 js 中获取最后 6 个项目

标签 javascript arrays reactjs ecmascript-6

我有一个数组,目前它在过滤后只包含今天的比赛后从数组中获取前 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/

相关文章:

javascript - "Uncaught TypeError: Cannot read property ' 在 p5.js 上绑定(bind) ' of undefined"

javascript 将正则表达式字符串转换为类型对象

java - 通过Rest WebService上传图像文件

python - 如何在 Python 中打乱多维列表

reactjs - 在 redux 状态的语言环境更新后重新渲染 React 组件

reactjs - 类型检查无状态组件中的 styled-components Prop

具有十进制增量的 Javascript For 循环输出错误

javascript - 当未选中表单提交时,复选框验证为 "on"

c - 理解 C 中的 gets() 函数

javascript - IE-graphql-SCRIPT5022 : Cannot use undefined "Boolean" from another module or realm