To fill an array with a static value in JavaScript, you can use the fill()
method available on Array objects. This method allows you to fill all the elements in an array with a specified static value.
The syntax for using fill()
method is as follows:
index.tsx28 chars2 lines
where
value
is the static value to fill the array withstart
(optional) is the index to start filling the array from (default is 0)end
(optional) is the index (exclusive) to stop filling the array at (default is array length)To fill an array with 5 elements with a static value of 0
, you can create a new array of size 5 and use the fill()
method as shown below:
index.tsx94 chars4 lines
In this example, we create a new array myArray
of size 5 using new Array(5)
and then use the fill()
method to fill all the elements with the static value of 0
. Finally, we log the array to the console, which outputs [0, 0, 0, 0, 0]
.
gistlibby LogSnag