首页 > 解决方案 > Getting last x elements in array not working

问题描述

Trying to use the answer from here: In a javascript array, how do I get the last 5 elements, excluding the first element?

I am using express / node.

I have

var texts = [{"id":1, "content":"one"}, {"id":2, "content":"two"},{"id":3, "content":"three", "id":4, "content":"four"];

In my get request, I tried responding like this:

app.get('/api/texts/', function (req, res, next) {
    res.json(texts.slice(3, 1));
    next();
});

but this responds with [] and nothing else. Any idea why?

edit:

app.get('/api/texts/', function (req, res, next) {
    res.json(texts);
    next();
});

The above properly prints out all the elements inside texts. It's just when I change it to res.json(texts.slice(3,1)); it prints out [].

标签: javascriptnode.jsexpress

解决方案


array.slice(x,y) 不能有 x < y。它总是会返回一个空数组。


推荐阅读