in javascript how would I create an empty array of a given size
Psuedo code:
X = 3;
createarray(myarray, X, \"\");
output:
We use Array.from({length: 500})
since 2017.
Try using while
loop, Array.prototype.push()
var myArray = [], X = 3;
while (myArray.length < X) {
myArray.push("")
}
Alternatively, using Array.prototype.fill()
var myArray = Array(3).fill("");
If you want to create anonymous array with some values so you can use this syntax.
var arr = new Array(50).fill().map((d,i)=>++i)
console.log(arr)
In 2018 and thenceforth we shall use [...Array(500)]
to that end.
As of ES5 (when this answer was given):
If you want an empty array of undefined
elements, you could simply do
var whatever = new Array(5);
this would give you
[undefined, undefined, undefined, undefined, undefined]
and then if you wanted it to be filled with empty strings, you could do
whatever.fill('');
which would give you
["", "", "", "", ""]
And if you want to do it in one line:
var whatever = Array(5).fill('');
var arr = new Array(5);
console.log(arr.length) // 5