/** * Create an array with `len` elements. * * @param [initFunc] Optional: a function that returns * the elements with which to fill the array. * If the function is omitted, all elements are `undefined`. * `initFunc` receives a single parameter: the index of an element. */ function initArray(len, initFunc) { if (typeof initFunc !== 'function') { // Yes, the return is uncessary, but more descriptive initFunc = function () { return undefined }; } var result = new Array(len); for (var i=0; i < len; i++) { result[i] = initFunc(i); } return result; } /* Interaction: > initArray(3) [ undefined, undefined, undefined ] > initArray(3, function (x) { return x }) [ 0, 1, 2 ] */