in javascript how would I create an empty array of a given size
Psuedo code:
X = 3;
createarray(myarray, X, "");
output:
myarray = ["","",""]
in javascript how would I create an empty array of a given size
Psuedo code:
X = 3;
createarray(myarray, X, "");
output:
myarray = ["","",""]
1) To create new array which, you cannot iterate over, you can use array constructor:
Array(100)
or new Array(100)
2) You can create new array, which can be iterated over like below:
a) All JavaScript versions
Array.apply(null, Array(100))
b) From ES6 JavaScript version
[...Array(100)]
Array(100).fill(undefined)
Array.from({ length: 100 })
You can map over these arrays like below.
Array(4).fill(null).map((u, i) => i)
[0, 1, 2, 3]
[...Array(4)].map((u, i) => i)
[0, 1, 2, 3]
Array.apply(null, Array(4)).map((u, i) => i)
[0, 1, 2, 3]
Array.from({ length: 4 }).map((u, i) => i)
[0, 1, 2, 3]
var arr = new Array(5);
console.log(arr.length) // 5
We use Array.from({length: 500})
since 2017.
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]
In newer versions, this now gives
[empty × 5]
See this other question on the difference between empty and undefined.
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('');
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("");
In 2018 and thenceforth we shall use [...Array(500)]
to that end.
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)
You can use both javascript methods repeat() and split() together.
" ".repeat(10).split(" ")
This code will create an array that has 10 item and each item is empty string.
const items = " ".repeat(10).split(" ")
document.getElementById("context").innerHTML = items.map((item, index) => index)
console.log("items: ", items)
<pre id="context">
</pre>
I've created benchmark tests for generating the empty arrays for iteration. The spread operator is the fastest. Array.from({length:n}) is the slowest.
https://www.measurethat.net/Benchmarks/Show/25596/1/compare-the-ways-to-generate-an-empty-array-for-iterati