JavaScript is not a strongly typed language like Java, so arrays don't need to be initialized. However we can still initialize an array if we would like.
To create a 1d array use new Array
:
let array = new Array(10) // An array with 10 items
You can then fill the array with a value using fill:
let array = new Array(10).fill('dog') // An array with 10 items with a value of dog
Taking the above, we can then initialize a 2d array by creating a new array with a set length and fill it with arrays. Since fill will take a value an use it once, we cannot pass new Array()
to fill. We will need to map the first array and change it's value to an array. Map takes a function so we just return a new array from the map and it will replace the original values with an array.
The result looks like this:
function initArray(rows, cols, filler = null) {
return [...new Array(rows)].map(() => new Array(cols).fill(filler))
}
// create an array with all nulls
let arr = initArray(2, 3)
console.log(JSON.stringify(arr))
// Change a value in the array
arr[0][1] = 'dog'
console.log(JSON.stringify(arr))
// Create an array with a filler
console.log(JSON.stringify(initArray(5, 2, 'dog')))
Note: Remember that since this is javascript and not java, the size of the array is not set in stone, and it is 100% possible to push more items onto the array making it larger than the specified size without error and javascript will not complain.