I want to fill a quantity, for example 9 elements of the array with the value of 0
let resultados = [];
resultados[0] = 0;
resultados[1] = 0;
resultados[2] = 0;
resultados[3] = 0;
resultados[4] = 0;
resultados[5] = 0;
resultados[6] = 0;
resultados[7] = 0;
resultados[8] = 0;
I want to generalize it to fill n elements in the array, is there a proper js function to do this? or should I do it with a loop to fill it?
The easiest way for me is the following:
where
len
is the length of your array and0
is the default value you want.One way is how you do it, initialize all elements with value 0.
But if you have created an array and regardless of the number of elements that your array contains, you can make a loop to modify the value of all its elements:
this way all the elements in your array would have the value of
0
.If you have already created your Array and want to initialize its values , another way is to use the method fill(value, start, end)
Example:
If you want to initially create your array containing 0 values , you can use the same fill() method like this:
This might help you:
It is a way of assigning the values when creating it.
In javascript, if you assign 10 parameters to a function of which only 4 have a value and you are going to add them to an array, if the function is unique it will add 10 values of which 4 have a value, but this is a method where the array is static.
If what you want is a dynamic array, you can choose to enter the values as a list, which requires a loop either inside the function or a loop calling the function, this last option is the most viable since your function just inputs a value and from where you call the function you control the size of the array.
From outside the function filling the array.
ECMASCRIPT 6
One of the most convenient changes is the possibility of defining an indeterminate number of parameters in assignment instructions, either as a function parameter or as a variable definition.