简体   繁体   中英

Does javascript have a range function?

Hi all i was just wondering if JS has a range function which will return numbers defined in an offset. I'm not using jQuery, so pure JS would be the best solution for me.

I want to get a set of numbers in sets of 5 ie

  1. First set of numbers - 0 - 4
  2. Second set of numbers - 5 - 10
  3. Third set of numbers - 11 - 16
  4. And so on and so on

I was wondering if this is possible at all? I was also looking at the underscore library to see if there's any handy methods but i couldn't find anything related to this at all.

You can use the underscore.js function _.range() :

_.range(10);
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11);
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5);
//=> [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1);
//=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
_.range(0);
// => []

See more here .

UPDATE

If you are using ES6, this is a native method of filling an array:

Array(range).fill().map((x,i)=>i);

For older versions of JavaScript, you could just create a for loop and add the values manually.

如果您正在使用ES6 / 2015,那么您也可以在纯JS中执行此操作(尽管有点凌乱:P)

Array(5).fill().map((x,i)=>i);

There's no reason to pull in the entire underscore.js library if this is the only function you need.

I'm assuming you're working with an array data structure. There is no range function in JavaScript but there are native array functions that you can use to get the same results.

I recommend using the slice method. For example, given the following:

var list = [1, 34, 5, 8, 13]

If we want the first three numbers (range of 0-2) , we can do:

list.slice(0,3)

The first argument to slice represents the index of the first number you want to include and the second argument is the ending index you want your range to include up to (but not including). This is a bit confusing and requires that you calculate and store the correct index values, so we should make up our own procedural abstraction.

We can write our own range function since that's really the proper abstraction in this context. Lets say that the first argument is the index you want to start at and the second argument is the size of the set.

var range = function (list, beginIndex, size) {
    return list.slice(beginIndex, beginIndex + size);
}

Using this function, we can get a set of numbers from any list. Using the example above using the concepts of a list, the starting index of the set, and the size of the set.

To get a set of 7 beginning form an index of 12:

range(list, 12, 7);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM