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