Javascript new array with length

Creating and filling Arrays of arbitrary lengths in JavaScript

Update 2019-01-02: Rewrote the section on performance. Switched from Array.from(new Array(LEN)) to Array.from() (because the former argument can get large). New sections: “Recommended patterns”, “Acknowledgements”.

The best way of creating an Array, is via a literal:

Alas, that isn’t always an option, e.g. when creating large Arrays. This blog post examines what to do in those cases.

Arrays without holes tend to perform better #

In most programming languages, an array is a contiguous sequence of values. In JavaScript, an Array is a dictionary that maps indices to elements. It can have holes – indices between zero and the length, that are not mapped to elements (“missing indices”). For example, the following Array has a hole at index 1:

Arrays without holes are also called dense or packed. Dense Arrays tend to perform better, because they can be stored contiguously (internally). Once there is at least one hole, the internal representation has to change. Two options are:

  • A dictionary. Then lookup takes more time and storage overhead is greater.
  • A contiguous data structure, with sentinel values for holes. Then checking if a value is a hole or not, takes extra time.

In either case, if an engine encounters a hole, it can’t just return undefined , it must traverse the prototype chain and search for a property whose name is the index of the hole. That costs even more time.

In some engines, such as V8, the switch to a less performant data structure is permanent. They won’t switch back, even if all holes are plugged.

For more on how V8 represents Arrays, consult “Elements kinds in V8” by Mathias Bynens.

Creating Arrays #

Array constructor #

One common way of creating an Array with a given length, is to use the Array constructor:

const LEN = 3; const arr = new Array(LEN); assert.equal(arr.length, LEN); // arr only has holes in it assert.deepEqual(Object.keys(arr), []); 

This approach is convenient, but it has two downsides:

  • The holes make this Array slightly slower, even if you completely fill it with values later on.
  • Holes are rarely good initial “values” for elements. E.g., zeros are much more common.

Array constructor plus .fill() method #

The .fill() method changes an existing Array and fills it with a specified value. That helps with initializing an Array after creating it via new Array() :

const LEN = 3; const arr = new Array(LEN).fill(0); assert.deepEqual(arr, [0, 0, 0]); 

Caveat: If you .fill() an Array with an object, all elements refer to the same instance (i.e., the object isn’t cloned):

const LEN = 3; const obj = <>; const arr = new Array(LEN).fill(obj); assert.deepEqual(arr, [<>, <>, <>]); obj.prop = true; assert.deepEqual(arr, [ prop:true>, prop:true>, prop:true> ]); 

We’ll later encounter a way of filling (via Array.from() ) that doesn’t have this issue.

Читайте также:  Java map size null

.push() method #

const LEN = 3; const arr = []; for (let i=0; i < LEN; i++) < arr.push(0); > assert.deepEqual(arr, [0, 0, 0]); 

This time, we have created and filled an Array without putting holes in it. Therefore, using the Array after its creation should be faster than with the Array constructor. Alas, creating the Array is slower, because engines may have to reallocate the contiguous internal representation several times – as it grows.

Filling Arrays with undefined #

Array.from() converts iterables and Array-like values to Arrays. It treats holes as if they were undefined elements. We can use that to convert each hole to an undefined :

> Array.from() [ undefined, undefined, undefined ] 

The parameter is an Array-like object with length 3 that contains only holes. It is also possible to instead use new Array(3) , but that usually creates larger objects.

Spreading into Arrays only works for iterable values and has a similar effect to Array.from() :

> [. new Array(3)] [ undefined, undefined, undefined ] 

Alas, Array.from() creates its result via new Array() , so you still end up with a sparse Array.

Mapping with Array.from() #

You can use Array.from() to map, if you provide a mapping function as its second parameter.

Filling an Array with values #

Creating ranges of integer values #

> const START=2, END=5; > Array.from(, (x, i) => i+START) [ 2, 3, 4 ] 

Another way of creating an Array with ascending integers is via .keys() , which also treats holes as if they were undefined elements:

.keys() returns an iterable. We use spreading to convert it to an Array.

Cheat sheet: creating Arrays #

Filled with holes or undefined :

  • new Array(3)
    → [ , , ,]
  • Array.from()
    → [undefined, undefined]
  • [. new Array(2)]
    → [undefined, undefined]

Filled with arbitrary values:

  • const a=[]; for (let i=0; i → [0, 0, 0]
  • new Array(3).fill(0)
    → [0, 0, 0]
  • Array.from(, () => (<>))
    → [<>, <>, <>] (unique objects)
  • Array.from(, (x, i) => i)
    → [0, 1, 2]
  • const START=2, END=5; Array.from(, (x, i) => i+START)
    → [2, 3, 4]
  • [. new Array(3).keys()]
    → [0, 1, 2]

I prefer the following approaches. My focus is on readability, not on performance.

    Do you need to create an empty Array that you’ll fill completely, later on?

Array.from(length: END-START>, (x, i) => i+START) 

If you are dealing with Arrays of integers or floats, consider Typed Arrays – which were created for this purpose. They can’t have holes and are always initialized with zeros.

Tip: Array performance usually doesn’t matter that much #

  • For most situations, I wouldn’t worry too much about performance. Even Arrays with holes are quite fast. It makes more sense to worry about your code being easy to understand.
  • Additionally, how and where engines optimize, changes. So what is fastest today, may not be tomorrow.

Acknowledgements #

Further reading #

Источник

javascript create empty array of a given size

1) To create new array which, you cannot iterate over, you can use array constructor:

2) You can create new array, which can be iterated over like below:

a) All JavaScript versions

b) From ES6 JavaScript version

  • Destructuring operator: [. Array(100)]
  • Array.prototype.fill Array(100).fill(undefined)
  • Array.from Array.from(< length: 100 >)
Читайте также:  Javascript unknown function parameters

You can map over these arrays like below.

  • Array(4).fill(null).map((u, i) => i) [0, 1, 2, 3]
  • [. Array(4)].map((u, i) => i) [0, 1, 2, 3]
  • Array.apply(null, Array(4)).map((u, i) => i) [0, 1, 2, 3]
  • Array.from(< length: 4 >).map((u, i) => i) [0, 1, 2, 3]

Enlightenment of the day — when you mention in part (A) that a newly created array using constructor syntax is not even iteratable. Javascript really surprises at times.

Its length is 10000, you can check it by console.log(Array(10000).length) But if you run Array(10000).forEach((u, i) => console.log(i)) , you will get no output

Array.apply(‘x’, Array(10)) is actually [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]

var arr = new Array(5); console.log(arr.length) // 5 

The OP asked in javascript how would I create an empty array of a given size . This solves that problem.

Well this is another option to the question. They can choose any of the answers provided, that’s the glory of stackoverflow 🙂

We use Array.from() since 2017.

@7vujy0f0hy I don’t know why you got down votes. I gave you an up vote, although your solution is a bit less intuitive than this one.

As of ES5 (when this answer was given):

If you want an empty array of undefined elements, you could simply do

[undefined, undefined, undefined, undefined, undefined] 

In newer versions, this now gives

See this other question on the difference between empty and undefined.

If you wanted it to be filled with empty strings, you could do

And if you want to do it in one line:

OK. There’s something else going on I don’t understand. I’m creating a new array with new Array(2) and what I get back is [ <2 empty items>] not [undefined, undefined] . Using .map on the former has no effect. However, I can iterate over it using a for. of loop. If I create a new array using literal notation a = [undefined, undefined] then I can use .map on it.

@JCF for. of uses iterator protocol, so it behaves differently than forEach/map. Iterators loose emptiness information

@TomaszBłachut @JCF For the down-voters, please keep in mind that this answer was given over 4 years ago – at which time, this answer was 100% valid. ES6 and ES7 did not start rolling out to browsers until mid-2016 and mid-2018, respectively. At the time of this answer, the JS version would have been ES5. If you need further proof that this is the way ES5 worked, simply spin up an older instance of Chrome – at the time of this answer, it would have been v48 – and run Array(5) . You will see the following output: [undefined x 5] .

@jeffdill2 It’s best to add new information to the answer itself. The comments are not always fully read.

Источник

Create Array of Specific Length in JavaScript

Create Array of Specific Length in JavaScript

  1. Create an Array of Length Using Array() Constructor in JavaScript
  2. Create an Array of Lengths Using the apply() Method in JavaScript
  3. Create an Array of Lengths Using the map() Method in JavaScript
  4. Creates an Array of Length Using the fill() Method in JavaScript

In JavaScript, you might need to create or declare an array of specific lengths and insert values you want inside the array. It can be achieved using different ways.

Below are some of the most ways to create an array of specific lengths in JavaScript. Now only use this in case you think there is a need for this because most of the time, there is no need to create or declare an array of specific lengths; you can dynamically make an array and use it.

Читайте также:  Линк для телефона html

Create an Array of Length Using Array() Constructor in JavaScript

The first way of creating an empty array of specific lengths is by using the Array() constructor and passing an integer as an argument to it. Since we are calling a constructor, we will be using the new keyword.

var arr = new Array(5); console.log(arr) 
[undefined, undefined, undefined, undefined, undefined] 

This way of creating an array of specific lengths is not recommended if you are using JSlint, as it might cause issues. Since this way is ambiguous and it does not just create an array of a particular length, it can also be used to do other things like creating an array containing a value as follows.

var arr_2 = new Array('5'); console.log(arr_2) 

Create an Array of Lengths Using the apply() Method in JavaScript

The Array constructor provides a method called apply() . Using this apply() method, you can provide arguments to a method in the form of an array. The apply() method takes two arguments, the first is the reference to this argument, and the second is the array.

var myArr = Array.apply(null, Array(5)); console.log(myArr); 
[undefined, undefined, undefined, undefined, undefined] 

To create an empty array of a specific length, let’s say 5 , we will pass null as the first argument, and the second is the array Array(5) . This will create an array of length 5 and initialize each element with an undefined value.

Alternatively, you can also do the following. Here, you can pass an array object as the second parameter and then inside it define the length of the array that you want to create, in this case, 5 .

var arr = Array.apply( null, < length: 5 > ); console.log(arr); console.log(arr.length); 
[undefined, undefined, undefined, undefined, undefined] 5 

Create an Array of Lengths Using the map() Method in JavaScript

Another way of creating an array of specific lengths is to use the map() method in JavaScript. Here, the Array(5) constructor will create an empty array of length 5. This is similar to what we saw previously. Then using the spread operator . , we will spread every element of the array and enclose this inside a square bracket like this [. Array(5)] . It will create an array of length 5 where the value of each element will be undefine . Then to initialize this array, we will make use of the map() method.

Using the map() method, we will take every element inside the x variable and then add value zero to it. This will initialize all the elements of the array to zero.

Creates an Array of Length Using the fill() Method in JavaScript

The fill() method also works the same way as map() does; the only thing is that the fill() does not take any function as a parameter. It directly takes a value as an input. You can create an array of specific length Array(5) and then fill the array with some integer value, as shown below.

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.

Related Article — JavaScript Array

Источник

Оцените статью