To pre-fill an array with 0s in JavaScript, you can use the Array.fill
method. The fill
method allows you to fill all elements in an array with a specified value. Here’s an example of how to pre-fill an array with 0s:
var array = new Array(5).fill(0);
In this example, we create a new array with 5 elements using the Array
constructor, and then call the fill
method on the array, passing in 0
as the value to fill the array with. The result is an array with 5 elements, all set to 0
.
You can also pre-fill an array with 0s using a for loop. Here’s an example:
var array = [];
var length = 5;
for (var i = 0; i < length; i++) {
array[i] = 0;
}
In this example, we create an empty array and use a for loop to fill the array with 0
s. The length
variable determines the size of the array, and the loop continues until the value of i
is equal to length
. The result is an array with length
elements, all set to 0
.
+ There are no comments
Add yours