Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 824
mithril333221 Avatar asked Feb 12 '12 03:02

mithril333221


People also ask

How do you create an array with N numbers?

To create an array with N elements containing the same value: Use the Array() constructor to create an array of N elements. Use the fill() method to fill the array with a specific value. The fill method changes all elements in the array to the supplied value.

How do you add elements to an array without overwriting the first one?

Another way to add/insert an element into an array is to use the . splice() method. With . splice() you can insert a new element at any given index, either overwriting what is currently in that index number, or inserting within, with no overwriting.

How do you create an array of numbers from 1 to N?

To create an array containing numbers from 1 to N:Create an empty array that will hold the numbers. Use a for loop to iterate N times, starting at 1 . For each iteration, push the loop's iteration index into the array.

Which is the correct way to create an array in JavaScript?

Creating an ArrayUsing an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.


1 Answers

I wouldn't worry too much about some random comment 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.

like image 55
Derek Park Avatar answered Oct 22 '22 21:10

Derek Park