I was toying a bit and was trying to instantiate a new array of length x
, where all elements of that array were initialized to a value y
:
var arr = new Array(x).fill(y);
This works well if the value of y
is anything other than an object. Meaning that if y
is an object, the following is true:
var arr = new Array(2).fill({}); arr[0] === arr[1]; //is true; arr[0].test = 'string'; arr[1].test === 'string'; //is also true;
Is there any way to state that a new object should be created for each element while using the fill-function? Or should I just convert it to a loop?
In JavaScript, you can use the Array. fill() method to populate an array with a zero or any other value like an object or a string. This method replaces all elements in an array with the value you want to populate the array with and returns the modified array.
Definition and Usage. The every() method executes a function for each array element. The every() method returns true if the function returns true for all elements.
The fill() method fills specified elements in an array with a value. The fill() method overwrites the original array. Start and end position can be specified. If not, all elements will be filled.
The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed.
You can first fill
the array with any value (e.g. undefined
), and then you will be able to use map
:
var arr = new Array(2).fill().map(u => ({}));
var arr = new Array(2).fill().map(Object);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With