Create a single value array in JavaScript
by new Array(21) you're actually creating an array with 21 elements in it.
If you want to create an array with single value '21', then it's:
var tech = [21];
alert(tech[0]);
new Array(21)
creates an array with a length of 21. If you want to create a single-value array, consisting of a number, use square brackets, [21]
:
var tech = [ 21 ];
alert(tech[0]);
If you want to dynamically fill an array, use the .push
method:
var filler = [];
for(var i=0; i<5; i++){
filler.push(i); //Example, pushing 5 integers in an array
}
//Filler is now equivalent to: [0, 1, 2, 3, 4]
When the Array constructor receives one parameter p
, which is a positive number, an array will be created, consisting of p elements. This feature is can be used to repeat strings, for example:
var repeat = new Array(10);
repeat = repeat.join("To repeat"); //Repeat the string 9x
You can create an Array with a value using Array.of
let arr = Array.of(8)
console.log(arr)
guys the answer was as simple as this:
<script>
var tech = new Array();
tech.push(21);
alert(tech[0]);
</script>