最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - return a range of values from an array in underscore.js - Stack Overflow

programmeradmin1浏览0评论

I have an array with the following data

var a = [1,2,3,4,5,6,7]

I am looking for a method in underscore.js or backbone.js in which I can return the elements with a specified range. for ex:

filter(2,5) should return  [3,4,5,6] 

which is the 2nd to 5th index elements in the array. Any pointers for me ?

I have an array with the following data

var a = [1,2,3,4,5,6,7]

I am looking for a method in underscore.js or backbone.js in which I can return the elements with a specified range. for ex:

filter(2,5) should return  [3,4,5,6] 

which is the 2nd to 5th index elements in the array. Any pointers for me ?

Share Improve this question edited Dec 15, 2015 at 22:36 Tito asked Apr 10, 2012 at 17:36 TitoTito 9,04413 gold badges55 silver badges87 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 33

Javascript Array should be defined like below,

var a = [1,2,3,4,5,6,7]; //not inside {}

And then you can use array native slice method to get elements from a specific position

a.slice(2, 6) //should return 3,4,5,6

Edit:

I very well know that the functionality is available in JScript. I was asking if its available in backbone or underscore. You are asking like why would you want an ice cube instead of water because ice will turn to water eventually.

Underscore js do not have function like slice as it is already available in native js.

Step 1:

Switch to Lodash. (https://lodash.com/)

Note: dangerous step, you will never go back.

Step 2:

Use the _.slice function like this:

_.slice(a, 2, 5)

发布评论

评论列表(0)

  1. 暂无评论