javascript - 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 []
.
解决方案
array.slice(x,y) 不能有 x < y。它总是会返回一个空数组。
推荐阅读
- c - 在其中增加一个指针和值存储
- ios - 内容可用的消息删除应用程序终止的先前消息
- python - len() 函数是否能够在 python 上使用 enumerate() 性能来增加 for 循环?
- r - 在 R 中,如何将数据框的列递归存储为数据框?
- excel - 如何使用打字稿合并excel在线文件?
- core-data - 从 Core Data 非标量属性更新 SwiftUI 视图
- reactjs - 尝试在 React/Redux 应用程序中注册用户时出现内部服务器错误
- flutter - 在 Flutter WebView 中编程“无连接”屏幕的最佳方法是什么?
- c++ - 为什么我的指针在 C++ 中变成了悬空指针?
- javascript - 如何为一系列 JavaScript if 语句创建后备?