问题
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.
Thanks in advance
回答1:
You really don't need a library for this.
var ary = ['thing1', 'thing2', 'thing3', 'thing4'];
var aryLength = ary.length;
var almostLast = ary[aryLength - 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.
If you need to use underscore, I guess you can use _.last()
as follows:
var lastTwo = _.last(ary, 2),
almostLast = lastTwo[0];
来源:https://stackoverflow.com/questions/31929651/plucking-an-object-in-an-array-using-underscore-js