【问题标题】:Getting last x elements in array not working获取数组中的最后一个 x 元素不起作用
【发布时间】:2019-02-04 02:16:08
【问题描述】:

尝试使用此处的答案: 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"];

在我的 get 请求中,我尝试这样响应:

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)); 时,它会打印出[]

【问题讨论】:

  • 1 小于 3
  • @Andy 在使用 get 请求之前,我使用推送请求将元素推送到数组。
  • [...'12345'].slice(3,1)//[] 预期的结果是什么?获取数组的最后N个索引,不包括数组的第一个索引?
  • 使用 for 循环...来吧!
  • 链接问题中的标记答案使用Math.max 从两个数字中选择一个数字。您的代码没有这样做。

标签: javascript node.js express


【解决方案1】:

array.slice(x,y) 不能有 x

【讨论】:

    猜你喜欢
    • 2013-06-24
    • 2022-09-29
    • 1970-01-01
    • 2011-09-09
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 2016-09-29
    相关资源
    最近更新 更多