Underscore.JS - range method



Syntax

_.range([start], stop, [step])

range method creates list of integers. We can configure this list using parameters passed. start is by default 0 and specifies the first element of list, stop is upto which elements are to be created in incremental order and elements are incremented using step. A step is by default 1. stop is not included in the list.

Example

var _ = require('underscore');

//Example 1: create an array of 5 elements
result = _.range(5);
console.log(result)

//Example 2: create an array of 5 elements from 5 to 10
result = _.range(5, 11);
console.log(result)

//Example 3: create an array of elements from 0 to 20(exclusive) with step 5
result = _.range(0, 20, 5);
console.log(result)

//Example 4: create an array of 5 negative elements
result = _.range(0, -5, -1);
console.log(result)

//Example 5: create an empty array
result = _.range(0);
console.log(result)

Save the above program in tester.js. Run the following command to execute this program.

Command

\>node tester.js

Output

[ 0, 1, 2, 3, 4 ]
[ 5, 6, 7, 8, 9, 10 ]
[ 0, 5, 10, 15 ]
[ 0, -1, -2, -3, -4 ]
[]
underscorejs_processing_array.htm
Advertisements