var a = [1,2,3,4,5];
var b = new Array(5);
Both of the above statements create an array with a length of five. The first has the values 1 through 5 in the entries 0 through 4 of that array while the second doesn't actually contain any entries. The first is a dense array where the number of entries and the length are equal while the second is a sparse array where the number of entries is less than the length.
Of course in both cases we can then run further code to change the content of the array to whatever we need it to be. The problem then is that you actually have more than one statement needed to create the array with the content that you want it to have and it isn't so obvious what the array contains.
We can make it easier to create arrays with actual content in them if we create some functions to create the arrays for us. In fact to make sure we remember that these are for creating arrays, let's add them as Array methods. Here are a few that I came up with:
1. A simple way to populate an array with values that correspond to the position within the array. So the following creates an array containing the numbers 0 through 49 in order. Simply change the 50 to the desired length and populate the array with as many numbers starting from zero as you want.
var c = .populate(50);
2. Since the above limits us to starting from zero, let's create a variant that allows you to specify the starting value as well. Both of these examples will load the array with the numbers -5 through 10 inclusive in ascending order.
var d = .range(-5,10);
var e = .range(10,-5);
3. Next let's make it easier to both specify the start and end values and allow for both ascending and descending order. This example produces the same result as the last one but with the numbers in the array in descending order.
var f = .to(-5);
4. Let's go one step further and not require the values we are loading to be integers. The following will produce an array of five values starting from 0 and ending with 2 with 0.5, 1 and 1.5 as the values in between.
var g = .intervals(0,5,0.5)
5. We don't have to limit ourselves to populating arrays with numbers. Another possibility is to load the letters of the alphabet in order simply starting over again from A each time we get to Z. In this example we go right through the alphabet once and then start over again and get to N by the time we have our 40 elements.
var h = .alpha(40);
6. For our last example we'll create an array that contain anything at all just as long as we want all of the array entries to start with the same value. In this example we create an array of 30 entries all of them containing 'Ab'.
var i = ['Ab'].repeat(30);
This article written by Stephen Chapman, Felgall Pty Ltd.