in javascript how would I create an empty array of a given size
Psuedo code:
X = 3;
createarray(myarray, X, "");
output:
myarray = ["","",""]
This question is related to
javascript
var arr = new Array(5);
console.log(arr.length) // 5
In 2018 and thenceforth we shall use [...Array(500)]
to that end.
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("");
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('');
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)
_x000D_
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)
_x000D_
<pre id="context">
</pre>
_x000D_
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]
We use Array.from({length: 500})
since 2017.
Source: Stackoverflow.com