Plucking an Object in an array using underscore.js

做~自己de王妃 提交于 2019-12-13 05:11:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!