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

标签 javascript arrays node.js

我有一个对象数组列表,我只想返回数组中的最后 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
  })
}

最佳答案

您可以使用Array#slice从末尾开始负索引。

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 }, { from: "mark", text: "long time", id: 10 }, { from: "clement", text: "yeah, indeed", id: 11 }];

console.log(welcomeMessage.slice(-6));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 我想从数组中获取最后 6 个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56314579/

相关文章:

javascript - 使用 Knockout-sortable 拖动 observableArray 项目时出现滞后

javascript - ES6 类方法可写吗?

javascript - 如何在不使用 'Cross Origin domain' chrome 扩展的情况下使用 Javascript 访问 JIRA REST API 来解决 'CORS' 问题

java - 为什么CopyOnWriteArrayList中没有这样的removeRange()方法?

node.js - Socket.io NodeJS 聊天 : Why do messages emit multiple times?

node.js - 无法在 mac 上使用 NPM 安装 lessc

javascript - 使用 Istanbul 尔的 nightwatch.js 的代码覆盖率

Java Arrays.equals() 为二维数组返回 false

c++ - 没有运算符 "="匹配这些操作数

javascript - RSQM - 手动轮询?