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?
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?
Share Improve this question asked Feb 12, 2012 at 3:09 mithril333221mithril333221 8192 gold badges10 silver badges20 bronze badges 8-
2
I actually think you're fine already. You're using the
[]
syntax when you allocate an array most of the time, andnew Array(n)
when you want a specific size. Nothing wrong there, the quote you posted doesn't account for all situations. – Michael Berkowski Commented Feb 12, 2012 at 3:13 - @Michael good to know!, I guess I can now sleep with the lights off :) – mithril333221 Commented Feb 12, 2012 at 3:16
-
1
I see nothing wrong with using the
Array
constructor in this manner. It exists for a good reason. – Jeremy Roman Commented Feb 12, 2012 at 3:18 -
@mithril333221 I'll check back in case someone enlightens me, but I don't know of another way to pre-allocate array size either short of
[null,null,null,null,...]
– Michael Berkowski Commented Feb 12, 2012 at 3:19 - 1 @LightnessRacesinOrbit on the ments of andrewdupont/2006/05/18/… – mithril333221 Commented Feb 12, 2012 at 3:32
4 Answers
Reset to default 5I wouldn't worry too much about some random ment on a blog in 2006. Especially since your use case isn't just new Array()
. You're using the special-case constructor that is provided specifically for this purpose.
Besides, using new Array()
instead of []
is hardly the worst thing someone can do with JS.
function repeat(str, len){
str= str || '';
len= len || 1;
return Array(len+1).join(str);
}
repeat('*',25)
// returned value: (String)
I know this question is pretty old, but here's how I would code it as an alternative to new Array(size), using JavaScript's literal syntax.
var arr = [];
arr.length = size;
You can use Array.from
to create an array with n elements.
Ex. Create array of zeros with length 7.
let arr = Array.from({length: 7}, () => 0);
!! Array.from
is not supported by IE so use with caution.