如何获取数组 Node.js 中的最后一项?

新手上路,请多包涵

我是 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)) : []

    }
  })
})

原文由 Benjamin Andersen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 592
2 个回答

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

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

非破坏性香草溶液:

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

或者,使用 lodash

 _.last(event.images);

原文由 psilocybin 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 .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

原文由 Ved 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题