Javascript 如何获取数组 Node.js 中的最后一项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45324032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get last item in array Node.js?
提问by Benjamin Andersen
I am new to node.js and JavaScript so this question might be quite simple but I cannot figure it out.
我是 node.js 和 JavaScript 的新手,所以这个问题可能很简单,但我无法弄清楚。
I have a lot of items in an array but only want to get the last item. I tried to use lodash but it somehow does not provide me with the last item in the array.
我在数组中有很多项目,但只想获取最后一个项目。我尝试使用 lodash 但它以某种方式没有为我提供数组中的最后一项。
My array looks like this now:
我的数组现在看起来像这样:
images : ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', ..., 'jpg.item_n']
and i want to get:
我想得到:
images : 'jpg.item_n'
Using lodash I am getting:
使用 lodash 我得到:
images : ['g.item_1', 'g.item_2', 'g.item_n']
It looks like I am just getting the last letter in jpg, i.e. 'g'.
看起来我刚刚得到了 jpg 中的最后一个字母,即“g”。
My code using lodash looks like this:
我使用 lodash 的代码如下所示:
const _ = require('lodash');
return getEvents().then(rawEvents => {
const eventsToBeInserted = rawEvents.map(event => {
return {
images: !!event.images ? event.images.map(image => _.last(image.url)) : []
}
})
})
回答by psilocybin
Your problem is that you're using _.lastinside map. This will get the last character in the current item. You want to get the last element of the actual Array.
你的问题是你正在使用_.lastinside map。这将获得当前项目中的最后一个字符。您想获取实际Array.
You can do this with pop(), however it should be noted that it is destructive (will remove the last item from the array).
您可以使用 来执行此操作pop(),但应注意它具有破坏性(将从数组中删除最后一项)。
Non-destructive vanilla solution:
无损香草解决方案:
var arr = ['thing1', 'thing2'];
console.log(arr[arr.length-1]); // 'thing2'
Or, with lodash:
或者,使用lodash:
_.last(event.images);
回答by Ved
Use .pop()array method
使用.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
回答by Dmitriy Simushev
Although Array.prototype.popretrieves the last element of the array it also removes this element from the array. So one should combine Array.prototype.popwith Array.prototype.slice:
虽然Array.prototype.pop检索数组的最后一个元素,但它也会从数组中删除该元素。因此,应该结合Array.prototype.pop使用Array.prototype.slice:
var images = ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', 'jpg.item_n'];
console.log(images.slice(-1).pop());

