I liked this question - Legitimate uses of the Function constructor - so I wanted to create a similar question regarding the Array
constructor.
Of course, the array literal notation is the correct way to create arrays. This would mean that the new Array
notation should not be used. And "case closed".
However, there is one specificity of the new Array
form. If a natural number is passed in, an empty array is created and its length
property is set to that number.
So
arr = new Array( 7 );
is equivalent to
arr = [];
arr.length = 7;
This can be considered a feature. I was wondering if this "feature" has real-world uses. I recently stumbled upon one such (simple) use:
new Array( n + 1 ).join( '*' ) // returns string containing n stars
// e.g.
new Array( 3 ).join( '*' ) // returns '**'
new Array( 6 ).join( '*' ) // returns '*****'
This is cool, but was hoping for some more advanced uses. (Something that would make the new Array
notation a legitimate tool in JavaScript programs.)
Update: I've noticed that the jQuery library uses the new Array( len )
notation in one instance - it's inside the when
function (search for "when:"
):
when: function( firstParam ) {
var args = sliceDeferred.call( arguments, 0 ),
i = 0,
length = args.length,
pValues = new Array( length ),
count = length,
pCount = length,
// etc.
They use it to initialize the pValues
local variable, which is used in a local function further down in the code:
function progressFunc( i ) {
return function( value ) {
pValues[ i ] = arguments.length > 1 ?
sliceDeferred.call( arguments, 0 ) : value;
deferred.notifyWith( promise, pValues );
};
}
I would love to know if changing the assignment to just
pValues = [],
would break the program... (Is new Array( length )
required for notifyWith
to work properly?)