Quantcast
Channel: JavaScript – iAdvise blog
Viewing all articles
Browse latest Browse all 14

5 Minute JavaScript #13: How to create an array from a range

$
0
0

Previous blogpost we discussed extending native data types in JavaScript. Today we’ll create a method in the array prototype that you can use to easily create a range such as an array.

Some programming languages allow you to easily create an array from a range, such as:

Scala

	val list = 0 until 10 toList

or Ruby

	arr = [0..10]

In JavaScript however, you need to use a for-loop to fill an array with ranged values. You could create a function that returns a filled array based on a from and to value like this:

function fill (from, to) {
 var a = [];
 for (var i = from; i <= to; i += 1) {
   a.push(i);
 }
 return a;
}

But then you have declared a function fill globally; that doesn’t really say much… it would be syntactically more interesting to use the Array prototype like this:

Array.prototype.fill = function (from, to) {
 var a = [];
 for (var i = from; i <= to; i += 1) {
   a.push(i);
 }
 return a;
};

Now we can create a new array using a very simple syntax

	var arr = [].fill(1,5); // results in [1,2,3,4,5]

While not perfect, defining the fill function this way, is a lot more readable. You start with an empty array and you fill it with a range of values. This makes perfect sense.



Viewing all articles
Browse latest Browse all 14

Latest Images

Trending Articles





Latest Images