问题描述
我有一个n个对象的数组.我想每次拔出最后一个对象.例如,我在一个数组中有4个对象.我希望使用underscore.jS摘除第三个对象.每次我想要将最后一个对象从数组中拔出时.
Hi i had an array with n number of objects. I want to pluck the last but one object every-time. For example i had 4 objects in an array. I want the third object to be plucked using underscore.jS. Every time i want the last but one object to be plucked out of an array.
预先感谢
推荐答案
您确实不需要为此使用的库.
You really don't need a library for this.
var ary = ['thing1', 'thing2', 'thing3', 'thing4'];
var aryLength = ary.length;
var almostLast = ary[aryLength - 2];
这适用于任何数组,而不仅限于此示例ary
.之所以有效,是因为数组是0索引的.在ary
,ary[0] = 'thing1'
,ary[1] = 'thing2'
等中,因此数组中的最后一个东西的索引号比其长度小2.
This works for any array, not just this example ary
. It works because arrays are 0-indexed. In ary
, ary[0] = 'thing1'
, ary[1] = 'thing2'
, etc. So the last thing in an array is available at the index of two less than its length.
如果您需要使用下划线,我想您可以按以下方式使用_.last()
:
If you need to use underscore, I guess you can use _.last()
as follows:
var lastTwo = _.last(ary, 2),
almostLast = lastTwo[0];
这篇关于使用underscore.js在数组中提取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!