【问题标题】:How to get last item in array Node.js? [duplicate]如何获取数组 Node.js 中的最后一项? [复制]
【发布时间】:2018-01-01 14:29:31
【问题描述】:

我是 node.js 和 JavaScript 的新手,所以这个问题可能很简单,但我无法弄清楚。

我在一个数组中有很多项,但只想获取最后一项。我尝试使用 lodash,但不知何故它没有为我提供数组中的最后一项。

我的数组现在看起来像这样:

images : ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', ..., 'jpg.item_n']

我想得到:

images : 'jpg.item_n'

使用 lodash 我得到:

images : ['g.item_1', 'g.item_2', 'g.item_n']

看起来我只是得到了 jpg 中的最后一个字母,即“g”。

我使用 lodash 的代码如下所示:

const _ = require('lodash');

return getEvents().then(rawEvents => {

  const eventsToBeInserted = rawEvents.map(event => {
    return {

      images: !!event.images ? event.images.map(image => _.last(image.url)) : []

    }
  })
})

【问题讨论】:

    标签: javascript arrays node.js


    【解决方案1】:

    您的问题是您在map 中使用_.last。这将获得当前项目中的最后一个字符。您想获取实际 Array 的最后一个元素。

    您可以使用pop() 执行此操作,但应注意它具有破坏性(将从数组中删除最后一项)。

    无损原版解决方案:

    var arr = ['thing1', 'thing2'];
    console.log(arr[arr.length-1]); // 'thing2'
    

    或者,lodash

    _.last(event.images);
    

    【讨论】:

    • 我明白了,这是有道理的。但是当我想在 eventsToBeInserted 中获得结果时,我该怎么做呢?
    • 你会做eventsTobeInserted.push(arr[arr.length-1])
    【解决方案2】:

    使用.pop()数组方法

    var images  =  ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', 'jpg.item_n'];
    
    var index= images.length - 1; //Last index of array
    console.log(images[index]);
    
    //or,
    
    console.log(images.pop())// it will remove the last item from array

    【讨论】:

    • 这将删除该项目,所以他不应该。
    • @NikxDa 正确。没想到。谢谢指点。
    【解决方案3】:

    虽然Array.prototype.pop 会检索数组的最后一个元素,但它也会从数组中删除该元素。所以应该将Array.prototype.popArray.prototype.slice 结合起来:

    var images  =  ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', 'jpg.item_n'];
    
    console.log(images.slice(-1).pop());
    

    【讨论】:

    • 关于否决票的任何意见? :)
    • 我这样做了:images: !! event.images ? event.images.map(image => image.url.slice(-1).pop()) : [],但现在我收到一条错误消息,提示 TypeError: image.url.slice(...).pop is not a function。不知道这意味着什么?
    • @BjarkeAndersen,很可能是因为 event.images 数组的格式错误。确保 image.url 也是一个数组。我为你准备了一个小例子:jsfiddle.net/enzam28p
    • 谢谢@Dmitriy Simushev
    猜你喜欢
    • 2014-09-26
    • 2011-03-14
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 2017-09-29
    • 1970-01-01
    • 2021-11-01
    相关资源
    最近更新 更多