Alex Rivera | Logout

Correct way to create an array with N number of elements without the old 'new Array(N)'?

Asked 2012-02-12T03:09:22.470
9

Whenever I work with arrays, I always use the [] style, however, when I want to create an array with a fixed amount of elements I use new Array(N) (I don't know any other way of doing this)

I thought it wasn't big deal, until I read these strong words about this:

Anyone doing this, using “new Array()” instead of “[]“, or “new Object()” instead of “{}” needs to relearn JavaScript.

I really want to avoid writting bad code. Anyone mind tell me the right direction to go?

Edit
Report

1 Answer

1
function repeat(str, len){
    str= str || '';
    len= len || 1;
    return Array(len+1).join(str);
}

repeat('*',25)

// returned value: (String)
answered 2012-02-12T05:15:56.140

Your Answer