为了账号安全,请及时绑定邮箱和手机立即绑定

我想从数组中获取最后 6 个对象

我想从数组中获取最后 6 个对象

千巷猫影 2021-06-09 14:10:04
我有一个对象数组列表,我只想返回数组中的最后 7 个对象。请帮助我尝试使用、过滤、映射和查找,但无法获得预期的输出var welcomeMessage = [{    from: "Clement",    text: "Welcome to Freeborn chat system!",    id: 0  },  {    from: "mark",    text: "Hello",    id: 1  },  {    from: "clement",    text: "welcome",    id: 2  },  {    from: "mark",    text: "long time",    id: 3  },  {    from: "clement",    text: "yeah, indeed",    id: 4  },  {    from: "mark",    text: "real good to be hear",    id: 5  },  {    from: "clement",    text: "you looking good",    id: 7  },  {    from: "mark",    text: "Hello",    id: 8  },  {    from: "clement",    text: "welcome",    id: 9  }]const messages = [welcomeMessage]function latestMessage(messages, search) {  let search = rquest.body;  let messages = messages.length - 7  const messages.filter(message => {    return message  })}
查看完整描述

3 回答

?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

让 lastSeven =welcomeMessage.slice(-7);


查看完整回答
反对 回复 2021-06-11
?
翻阅古今

TA贡献1780条经验 获得超5个赞

上面的答案是正确的,也是最好的解决方案,但是如果您需要使用过滤器,您可以执行以下操作:


const items = welcomeMessage.filter((obj, index) => {

    const arrayLength = welcomeMessage.length;

    const wantedItems = 6;

    return arrayLength - index <= wantedItems;

});


查看完整回答
反对 回复 2021-06-11
  • 3 回答
  • 0 关注
  • 266 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信