gpt4 book ai didi

javascript - 获取数组中的最后 x 元素不起作用

转载 作者:行者123 更新时间:2023-12-01 01:18:13 24 4
gpt4 key购买 nike

尝试使用这里的答案: In a javascript array, how do I get the last 5 elements, excluding the first element?

我正在使用express/node。

我有

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

在我的获取请求中,我尝试像这样响应:

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

但这仅响应 [] 而没有其他内容。知道为什么吗?

编辑:

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

上面正确打印了 texts 中的所有元素。只是当我将其更改为 res.json(texts.slice(3,1)); 时,它会打印出 []

最佳答案

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

关于javascript - 获取数组中的最后 x 元素不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54509435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com